Best Time to Buy and Sell Stock with Cooldown (LeetCode 309): Solution and Explanation
You know a stock's price on each day and may make as many buy and sell transactions as you like, holding at most one share. The twist is that after selling you must wait one full day before buying again, and you want the maximum total profit.
Watch it run step by step
Try your own input and write the code →Intuition
Without the cooldown, the answer is just the sum of every upward price move. The cooldown breaks that greedy idea, because selling today blocks buying tomorrow, so a sale now can cost you a better opportunity later. A brute force recursion that tries buy, sell or wait on every day is exponential, which points toward dynamic programming over days.
The trick is to describe where you can be at the end of each day. You are either holding a share (hold), you just sold today (sold), or you have no share and are free to buy (rest). Each state's best profit today depends only on yesterday's states, so you can track three numbers instead of a table.
The transitions encode the rules directly. You hold today if you held yesterday or bought today, and buying requires that yesterday you were in rest, which is how the cooldown is enforced. You are in sold today only by selling a share you held yesterday. You are in rest today if you rested yesterday or sold yesterday, because the day after a sale is the forced cooldown. The answer is the better of ending in sold or rest, since ending while holding a share is never optimal.
Approach: Three-state dynamic programming
- If there are one or fewer prices, no profit is possible, so return 0.
- Initialize
hold = -prices[0](bought on day 0),sold = 0andrest = 0. - For each later day, save
prev_hold = holdbecausesoldneeds yesterday's value. - Update
hold = max(hold, rest - prices[i]), whererestis still yesterday's value. - Update
rest = max(rest, sold), wheresoldis still yesterday's value. - Update
sold = prev_hold + prices[i], and after the loop returnmax(sold, rest).
Step-by-step example
prices = [1, 2, 3, 0, 2]
- Start with
hold = -1,sold = 0,rest = 0. - Day 1 (price 2):
hold = max(-1, 0 - 2) = -1,rest = 0,sold = -1 + 2 = 1. - Day 2 (price 3):
hold = -1,rest = max(0, 1) = 1,sold = -1 + 3 = 2. - Day 3 (price 0):
hold = max(-1, 1 - 0) = 1(sold on day 1, cooled down on day 2, bought now),rest = max(1, 2) = 2,sold = -1 + 0 = -1. - Day 4 (price 2):
hold = max(1, 2 - 2) = 1,rest = max(2, -1) = 2,sold = 1 + 2 = 3. - The answer is
max(3, 2) = 3: buy at 1, sell at 2, cool down, buy at 0, sell at 2.
Code: Python, Java, C++
1class Solution:
2 def maxProfit(self, prices: List[int]) -> int:
3 if len(prices) <= 1:
4 return 0
5 hold = -prices[0]
6 sold = 0
7 rest = 0
8 for i in range(1, len(prices)):
9 prev_hold = hold
10 hold = max(hold, rest - prices[i])
11 rest = max(rest, sold)
12 sold = prev_hold + prices[i]
13 return max(sold, rest)1class Solution {
2 public int maxProfit(int[] prices) {
3 if (prices.length <= 1) return 0;
4 int hold = -prices[0];
5 int sold = 0;
6 int rest = 0;
7 for (int i = 1; i < prices.length; i++) {
8 int prevHold = hold;
9 hold = Math.max(hold, rest - prices[i]);
10 rest = Math.max(rest, sold);
11 sold = prevHold + prices[i];
12 }
13 return Math.max(sold, rest);
14 }
15}1class Solution {
2public:
3 int maxProfit(vector<int>& prices) {
4 if (prices.size() <= 1) return 0;
5 int hold = -prices[0];
6 int sold = 0;
7 int rest = 0;
8 for (int i = 1; i < prices.size(); i++) {
9 int prevHold = hold;
10 hold = max(hold, rest - prices[i]);
11 rest = max(rest, sold);
12 sold = prevHold + prices[i];
13 }
14 return max(sold, rest);
15 }
16};Time and space complexity
O(n)
The loop visits each day once and does a constant number of max operations.
O(1)
Only three state variables and one temporary are kept, regardless of the number of days.
Other approaches
DP arrays per state (time O(n), space O(n))
Keep arrays hold[i], sold[i] and rest[i] for every day. It is easier to debug and print, but uses linear memory for the same recurrence.
Two-variable form with i - 2 lookback (time O(n), space O(1))
Define buy[i] = max(buy[i - 1], sell[i - 2] - prices[i]) and sell[i] = max(sell[i - 1], buy[i - 1] + prices[i]). The cooldown is expressed by looking back two days instead of using a rest state.
Common mistakes
- Updating
soldfrom the newholdinstead ofprev_holdlets you buy and sell on the same day using the just-updated value. - Computing
restbeforeholdmeansholdreads today's rest, which may include a sale from yesterday and silently removes the cooldown. - Returning
max(hold, sold, rest)is harmless but returningholdalone is wrong, since you never want to end the last day still holding a share. - Initializing
holdto 0 instead of-prices[0]pretends you got the first share for free.
Frequently asked questions
How does the cooldown change the DP?
Buying is only allowed from the rest state, and the rest state today comes from resting or selling yesterday. That forces at least one day between a sale and the next purchase.
Why are there three states?
At the end of any day you either hold a share, have just sold, or are idle without a share. Separating just sold from idle is what lets the recurrence know whether today's buy is legal.
Can this be solved greedily like Stock II?
No. Summing every rising day assumes you can sell and rebuy on the same or next day, which the cooldown forbids. You need the DP to weigh a sale now against a better buy later.
What is the space complexity?
O(1). Each state depends only on the previous day's states, so three variables replace the full DP table.