sagelearnai

Best Time to Buy and Sell Stock with Cooldown

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #309

Trade as often as you like, holding at most one share, but after you sell you must wait one day (cooldown) before buying again. Return the maximum profit.

Examples

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

Hints

  1. On any day you're in one of three states: holding a share, just sold (in cooldown tomorrow), or resting with no share and free to buy.
  2. Write how each state can be reached from yesterday's states.

Approach

State machine:

text
hold' = max(hold, rest - p)    # keep holding, or buy (only from rest)
sold' = hold + p               # sell today
rest' = max(rest, sold)        # stay idle, or finish a cooldown

Start with hold = −∞, sold = 0, rest = 0. The answer is max(sold, rest). Compute all three from the previous day's values, using temporaries. The two-state template from the fee and II variants extends cleanly by adding one state per rule.

Complexity

Time: O(n). Space: O(1).

Python solution
def maxProfit(prices):
    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)
JavaScript solution
function maxProfit(prices) {
  let hold = -Infinity, sold = 0, rest = 0;
  for (const p of prices) [hold, sold, rest] = [Math.max(hold, rest - p), hold + p, Math.max(rest, sold)];
  return Math.max(sold, rest);
}