#309

Best Time to Buy and Sell Stock with Cooldown

Medium State machine DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Trade as many times as you like, holding at most one share, but after selling you must wait one day before buying again. Maximise profit.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: unlimited trades, but a day of rest after selling.

Why this works: three states per day: holding, just sold, resting. You may only buy from resting.

Example: [1, 2, 3, 0, 2]

buy 1, sell 2, cooldown, buy 0, sell 2 → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Buying from yesterday's "sold" state — that skips the cooldown.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon