AlgoViz

Best Time to Buy and Sell Stock with Cooldown

Medium

Three states: holding, sold, free

Problem

Maximize profit with unlimited transactions but a one-day cooldown after selling.

In simple words

Three states (holding, just-sold, resting); after selling you must rest a day before buying again.

The idea

After selling you must sit out a day, so the state machine needs a distinct 'just sold' state that cannot buy tomorrow. Buying is only allowed from the free state, which encodes the cooldown exactly.

The trick

  • hold, sold, rest — buy transitions only from rest.
  • sold moves to rest the next day; it cannot buy directly.
  • O(n) time, O(1) space.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

1
2
3
0
2
0
1
2
3
4

Step 1 of 2. Here's the example — [1,2,3,0,2] Values: 1, 2, 3, 0, 2.

1/2
Optimal
timeO(n)spaceO(1)
1states hold, buy, sell2sell today needs buy yesterday; buy needs a rest day before

Input

array
[1, 2, 3, 0, 2]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Explanation:
Buy, sell, cooldown, buy, sell → 3.

Example 2

Input:
prices = [1]
Output:
0
Explanation:
One day → 0.

Example 3

Input:
prices = [2, 1, 4]
Output:
3
Explanation:
Buy at 1, sell at 4 → 3.

Finished the walkthrough? Add it to your streak.