SDE & MLE Prep

309. Best Time to Buy and Sell Stock with Cooldown

Problem

prices[i] is a stock's price on day i. Make as many buy-then-sell transactions as you like, holding at most one share at a time, but after selling you can't buy on the next day (one-day cooldown). Return the maximum profit.

Example: [1,2,3,0,2] → 3 (buy, sell, cooldown, buy, sell)

Three states per day: hold (own a share), sold (just sold today → cooldown tomorrow), rest (free, not holding).

          buy               sell
  rest ---------> hold ------------> sold
   ^  \__/          \__/              |
   |  stay          stay              |
   +---------- cooldown --------------+

Complexity: O(n) time, O(1) space.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        hold, sold, rest = float("-inf"), 0, 0
        for p in prices:
            hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
        return max(sold, rest)