Best Time to Buy and Sell Stock with Cooldown - Problem
Imagine you're a stock trader with access to future price information, but there's a catch - every time you sell stock, you must take a mandatory one-day vacation (cooldown period) before you can buy again!
Given an array prices where prices[i] represents the stock price on day i, your goal is to maximize your profit by strategically buying and selling shares.
Trading Rules:
- π You can complete unlimited transactions (buy-sell pairs)
- βΈοΈ After selling, you must wait one day before buying again
- π« You cannot hold multiple shares simultaneously
- π° Each transaction consists of buying one share and later selling it
Example: If prices = [1,2,3,0,2], you could buy on day 0 (price=1), sell on day 2 (price=3), cooldown on day 3, buy on day 3 (price=0), and sell on day 4 (price=2) for a total profit of (3-1) + (2-0) = 4.
Input & Output
example_1.py β Basic Trading
$
Input:
[1,2,3,0,2]
βΊ
Output:
3
π‘ Note:
Buy on day 0 (price=1), sell on day 2 (price=3), profit = 3-1 = 2. Then buy on day 3 (price=0), sell on day 4 (price=2), profit = 2-0 = 2. Total profit = 2 + 2 = 4. Wait, that's wrong - we need cooldown! Correct: Buy day 0 (price=1), sell day 2 (price=3), cooldown day 3, buy day 4 would be invalid. Optimal: buy day 0, sell day 1 (profit=1), cooldown day 2, buy day 3, sell day 4 (profit=2). Total = 3.
example_2.py β No Profit Scenario
$
Input:
[1]
βΊ
Output:
0
π‘ Note:
Only one day, so no transactions possible. Maximum profit is 0.
example_3.py β Declining Prices
$
Input:
[5,4,3,2,1]
βΊ
Output:
0
π‘ Note:
Prices are continuously declining, so buying any day and selling later would result in loss. Best strategy is to not trade at all, profit = 0.
Visualization
Tap to expand
Understanding the Visualization
1
Start in REST state
Day 0: We can buy stock, transitioning to HELD state
2
HELD state decisions
Each day: Hold stock or sell (go to SOLD state)
3
SOLD state cooldown
Must go to REST state next day (mandatory cooldown)
4
REST state options
Can stay in REST or buy stock (go to HELD)
5
Track maximum profit
For each state, keep the maximum profit achievable
Key Takeaway
π― Key Insight: Model the problem as a state machine with three states (HELD, SOLD, REST) and track the maximum profit achievable in each state at every day.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the prices array
β Linear Growth
Space Complexity
O(1)
Only storing three state variables
β Linear Space
Constraints
- 1 β€ prices.length β€ 5000
- 0 β€ prices[i] β€ 1000
- Cooldown constraint: After selling, must wait one day before buying
- No simultaneous transactions: Must sell before buying again
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code