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
Best Time to Buy and Sell Stock with Cooldown INPUT Stock Prices Over 5 Days 0 1 2 3 Day 0 Day 1 Day 2 Day 3 Day 4 prices array: 1 2 3 0 2 [0] [1] [2] [3] [4] Cooldown: 1 day after sell ALGORITHM STEPS 1 Define 3 States hold, sold, rest hold sold rest 2 State Transitions hold = max(hold, rest-price) sold = hold + price rest = max(rest, sold) 3 Process Each Day Update states in order Day Price hold sold rest 0 1 -1 -inf 0 1 2 -1 1 0 2 3 -1 2 1 3 0 1 1 2 4 Return max(sold, rest) Day 4: max(3, 2) = 3 FINAL RESULT Optimal Transactions Transaction 1 Buy @ Day 0 (price=1) Sell @ Day 2 (price=3) +2 Day 3: COOLDOWN (no buy) Transaction 2 Buy @ Day 3 (price=0) Sell @ Day 4 (price=2) +2 Max Profit 3 Output: 3 -- OK (2 - 1) + (2 - 0) = 3 Key Insight: Use 3 states (hold, sold, rest) to track maximum profit at each day. The cooldown constraint is handled by making 'hold' transition only from 'rest' state (not from 'sold'). This state machine approach gives O(n) time and O(1) space complexity. TutorialsPoint - Best Time to Buy and Sell Stock with Cooldown | Optimal Solution (State Machine DP)
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