Best Time to Buy and Sell Stock with Cooldown - Problem

You are given an array prices where prices[i] is the price of a given stock on the i-th day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
  • You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Input & Output

Example 1 — Basic Transaction Pattern
$ Input: prices = [1,2,3,0,2]
Output: 3
💡 Note: Buy on day 0 (price=1), sell on day 2 (price=3), cooldown on day 3, buy on day 3 (price=0), sell on day 4 (price=2). Total profit = (3-1) + (2-0) = 4. Wait, that's wrong. Actually: buy day 0 (price=1), sell day 2 (price=3) for profit 2, cooldown day 3, buy day 3 (price=0) is impossible since we're in cooldown. Correct: buy day 0, sell day 2, profit=2. Or buy day 3, sell day 4, profit=2. Or buy day 0, sell day 1, profit=1, cooldown day 2, buy day 3, sell day 4, profit=2, total=3.
Example 2 — All Increasing Prices
$ Input: prices = [2,4,1]
Output: 2
💡 Note: Buy on day 0 (price=2), sell on day 1 (price=4). Profit = 4-2 = 2. Cannot buy on day 2 due to cooldown, and price is lower anyway.
Example 3 — Single Transaction Only
$ Input: prices = [1,2]
Output: 1
💡 Note: Buy on day 0 (price=1), sell on day 1 (price=2). Profit = 2-1 = 1.

Constraints

  • 1 ≤ prices.length ≤ 5000
  • 0 ≤ prices[i] ≤ 1000

Visualization

Tap to expand
Stock Trading with Cooldown: [1,2,3,0,2]12302Day 0Day 1Day 2Day 3Day 4BUYSELLCOOLDOWNProfit: 3-1 = 2Trading Rules✓ Buy and sell multiple times✓ Must sell before buying again✗ Cannot buy day after selling✗ Cooldown period requiredChallenge: Find optimal buy/sell timing with cooldown constraintMaximum Profit: 3
Understanding the Visualization
1
Input
Array of stock prices over time
2
Constraint
Must cooldown one day after selling
3
Output
Maximum profit achievable
Key Takeaway
🎯 Key Insight: Model as state machine with three states: holding, sold (cooldown), and resting
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
156.0K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen