PracticeNeetCode ↗LeetCode ↗
Given daily stock prices, maximize profit from any number of buy/sell transactions (never holding more than one share at a time), with the rule that after selling you must wait one full day before buying again.
hold = -infinity (haven't bought yet), sold = 0, rest = 0.sold value first.sold to hold + price (sell what you're holding today).hold to max(hold, rest - price) (keep holding, or buy today from a resting state).rest to max(rest, yesterday's sold) — cooldown means resting can only refresh from a sale that happened before today.max(sold, rest) — ending while still holding is never optimal.Time: O(n) — Space: O(1)
def maxProfit(prices: list[int]) -> int:
hold, sold, rest = float("-inf"), 0, 0
for price in prices:
prev_sold = sold
sold = hold + price
hold = max(hold, rest - price)
rest = max(rest, prev_sold)
return max(sold, rest)How the solution above works, piece by piece.
hold (own a share), sold (just sold today), rest (no share, allowed to buy).sold = hold + price: selling today requires holding yesterday.hold = max(hold, rest - price): keep holding, or buy today, but only from rest. Buying from yesterday's sold is not allowed, which is the cooldown rule.rest = max(rest, prev_sold): stay resting, or come out of yesterday's cooldown. prev_sold keeps yesterday's value because sold was already overwritten.max(sold, rest) (ending while holding is never best). O(n) time, O(1) space.Running it on prices = [1, 2, 3, 0, 2]:
sold can only come from hold, and buying can only happen from rest, never straight after a sale: that's the cooldown. On the last day the best is max(sold = 3, rest = 2) = 3.NeetCode — Best Time to Buy and Sell Stock with Cooldown, LeetCode 309