mediumDynamic ProgrammingDynamic Programming

Best Time to Buy and Sell Stock with Cooldown

mediumTime: O(n)Space: O(1)

Recognize the pattern

buy/sell stock with cooldown after sellingstate machine: hold/sold/cooldowncan't buy immediately after sell

Brute force idea

A straightforward first read of Best Time to Buy and Sell Stock with Cooldown is this: Try all buy/sell/cooldown sequences. Three choices at each day. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Best Time to Buy and Sell Stock with Cooldown comes when you notice this: State DP: track three states per day — hold (own stock), sold (just sold), cooldown (resting). Transitions: hold = max(prevHold, prevCooldown - price), sold = prevHold + price, cooldown = max(prevCooldown, prevSold). Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Best Time to Buy and Sell Stock with Cooldown is this: Three states capture all possibilities. The cooldown state enforces the one-day waiting period after selling. Each state depends only on the previous day's states. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in Best Time to Buy and Sell Stock with Cooldown is this: Forgetting that you can't buy the day after selling — that's what the cooldown state enforces. Without it, you'd accidentally allow immediate re-buying. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Dynamic Programming Pattern