Visualize

Pattern visualizer

Buy and Sell Stock with Cooldown

Every day you are in exactly one of three states: holding a share, having just sold one (which forces tomorrow to be a rest day), or resting with nothing held. Each state's best profit only depends on yesterday's states, so track three running values — hold, sold, rest — and update all three every day from yesterday's numbers. The cooldown rule shows up as one missing edge: today's hold can come from yesterday's rest but never from yesterday's sold, since selling and immediately buying the next day is exactly what cooldown forbids. Animated on: prices = [1, 2, 3, 0, 2] — after selling you must cooldown for one day before buying again. Find the max profit..

Three running states per day: hold, sold-today, resting

time O(n)space O(n)step 1 / 14

prices = [1, 2, 3, 0, 2]

line 3

Day 0 base case: hold[0] = -1 (buying today is the only way to hold), sold[0] = 0 and rest[0] = 0 (no trade has happened yet, so no profit either way).

Pseudocode
1FUNCTION maxProfit(prices):
2 n <- LENGTH(prices)
3 hold[0] <- -prices[0]
4 sold[0] <- 0
5 rest[0] <- 0
6 FOR i FROM 1 TO n-1:
7 hold[i] <- MAX(hold[i-1], rest[i-1] - prices[i])
8 sold[i] <- hold[i-1] + prices[i]
9 rest[i] <- MAX(rest[i-1], sold[i-1])
10 RETURN MAX(sold[n-1], rest[n-1])

← / → step · space play · Home restart

Where to practice Dynamic Programming