Leetcode 309 Solution

This article provides solution to leetcode question 309 (best-time-to-buy-and-sell-stock-with-cooldown).

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown

Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        last_own = 0
        last_sell = 0
        last_rest = 0
        
        ans = 0
        for i, price in enumerate(prices):
            if i == 0:
                last_own = -price
                last_sell = 0
                last_rest = 0
            else:
                next_own = max(last_own, last_rest - price)
                next_sell = last_own + price
                next_rest = max(last_rest, last_sell)
                
                last_own = next_own
                last_sell = next_sell
                last_rest = next_rest
            
            ans = max(ans, last_sell)
            
        return ans