15% off all plans & roadmaps Use code
See plansBest Time to Buy and Sell Stock with Cooldown
- LeetCode 309
- Medium
- Dynamic Programming (DP) Patterns
- Stock problems
Updated
TL;DR: You may buy and sell a stock many times, but you must rest one day after every sale. Track the best profit in three states (holding, sold today, free to buy) and update them once per day in O(n) time and O(1) space.
Problem
You are given an array prices, where prices[i] is the price of a stock on day i.
Find the maximum profit you can make. You may complete as many transactions as you like (buy one share, then sell one share, repeatedly), with this restriction: after you sell, you cannot buy on the very next day. That next day is a cooldown day.
You may not hold more than one share at a time. You must sell the share you own before you buy again.
Example 1
Input: prices = [1,2,3,0,2] Output: 3 Explanation: the transactions are buy, sell, cooldown, buy, sell.
Example 2
Input: prices = [1] Output: 0
Constraints
1 <= prices.length <= 50000 <= prices[i] <= 1000
Constraints that matter
prices.lengthup to 5000 rules out the exponential recursion, which branches on every day, and allows any O(n) or even O(n^2) method.- Only one extra day of lag matters (the cooldown), so each day depends on the previous day or two days back. That is why three running numbers are enough and no full table is required.
prices[i]is at most 1000 and n is at most 5000, so the profit is at most about 5,000,000. A 32-bit integer cannot overflow.prices.length >= 1means you never handle an empty array, but a single price must return 0 because you cannot sell after buying on the same day.- Prices are non-negative, so holding a share has a cost of at most 1000 and negative profits only appear in the holding state, never in the final answer.
Hints
Hint 1
This is a dynamic programming problem on a stock timeline, usually called a state machine DP.
Hint 2
Try every legal sequence of actions.
Solution
Intuition
This is a dynamic programming problem on a stock timeline, usually called a state machine DP. Each day you choose to buy, sell or wait, and the choice you may make depends on what you did earlier. That dependence is the hint to define a small set of states and track the best profit for each.
Picture three labeled jars on a shelf, each holding the best profit so far for one state, and each day you pour from yesterday's jars into today's. The rest jar only gets filled from the sold jar, so a buy can never pour straight out of sold, which is the cooldown.
Without the cooldown, two states are enough: holding a share or not. The cooldown breaks that. Being empty-handed after a sale is different from being empty-handed after a rest day, because only the second lets you buy tomorrow. So you split the empty-handed state in two, which gives three states: hold, sold (you sold today), and rest (empty-handed and free to buy).
The transitions follow directly. You can only buy from rest. You can only sell from hold. After sold, you must move to rest the next day.
Each state keeps the maximum profit over all ways to reach it. Every valid plan is covered, and every invalid plan (buying right after a sale) is impossible by construction.
Because day i reads only from day i - 1, you never need a table. Three variables rolled forward each day give O(n) time and O(1) space.
Worked example
Input: prices = [1, 2, 4, 2, 5, 7, 2, 4, 9, 0] Output: 11 Explanation: Buy on day 0 at 1 and sell on day 5 at 7 for a profit of 6. Rest on day 6. Buy on day 7 at 4 and sell on day 8 at 9 for a profit of 5. The total is 6 + 5 = 11.
Approach 1: Brute force recursion
Try every legal sequence of actions. At day i, you either hold a share or you do not. If you do not hold, you may skip the day or buy. If you hold, you may skip the day or sell, and a sale sends you to day i + 2 because day i + 1 is the cooldown.
The cooldown is handled by jumping two days ahead after a sale, so you need no third flag. The answer is the best total over all paths.
Steps
- Define
go(i, holding)as the best profit obtainable from dayionward in the given holding state. - If
iis past the last day, return 0. - Start with the skip option:
go(i + 1, holding). - If holding, try selling:
prices[i] + go(i + 2, false). The jump toi + 2skips the cooldown day. - If not holding, try buying:
-prices[i] + go(i + 1, true). - Return the larger option and call
go(0, false).
Dry run
Trace on [1,2,4,2,5,7,2,4,9,0]. The call go(0, false) branches into skip (go(1, false)) and buy (-1 + go(1, true)). Each of those branches again, so the tree has about 2^n leaves.
One path in the tree is: buy on day 0 (-1), skip days 1 to 4, sell on day 5 (+7), jump to day 7, buy (-4), sell on day 8 (+9), jump to day 10, return 0. That path totals -1 + 7 - 4 + 9 = 11.
No other path beats it, so the maximum over all branches is 11. The same pair (i, holding) such as (7, false) is reached again and again by different earlier choices, which is the wasted work.
Complexity
| Time | O(2^n) |
|---|---|
| Space | O(n) |
Here n is the number of days. Each call makes up to two recursive calls and the depth can reach n, so the call tree can hold on the order of 2^n nodes. The only memory used is the call stack, which is at most n frames deep.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
# free[i] = go(i, False), hold[i] = go(i, True); the recursion memoized bottom-up
free = [0] * (n + 2)
hold = [0] * (n + 2)
for i in range(n - 1, -1, -1):
# skip or buy
free[i] = max(free[i + 1], -prices[i] + hold[i + 1])
# skip or sell (cooldown: continue at i + 2)
hold[i] = max(hold[i + 1], prices[i] + free[i + 2])
return free[0]
JavaTested in our runner
import java.util.*;
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
// memo[i][h]: best profit from day i with holding state h (Integer.MIN_VALUE = not computed)
int[][] memo = new int[n][2];
for (int[] row : memo) Arrays.fill(row, Integer.MIN_VALUE);
return go(prices, 0, 0, memo);
}
private int go(int[] p, int i, int holding, int[][] memo) {
if (i >= p.length) return 0;
if (memo[i][holding] != Integer.MIN_VALUE) return memo[i][holding];
int best = go(p, i + 1, holding, memo); // skip the day
if (holding == 1) {
// sell today, cooldown tomorrow, continue at i + 2
best = Math.max(best, p[i] + go(p, i + 2, 0, memo));
} else {
// buy today
best = Math.max(best, -p[i] + go(p, i + 1, 1, memo));
}
memo[i][holding] = best;
return best;
}
}C++Tested in our runner
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
// memo[i][h]: best profit from day i in holding state h
vector<vector<int>> memo(prices.size(), vector<int>(2, INT_MIN));
return go(prices, 0, 0, memo);
}
private:
int go(vector<int>& p, int i, int holding, vector<vector<int>>& memo) {
if (i >= (int)p.size()) return 0;
int& res = memo[i][holding];
if (res != INT_MIN) return res;
int best = go(p, i + 1, holding, memo); // skip the day
if (holding) {
// sell today, cooldown tomorrow, continue at i + 2
best = max(best, p[i] + go(p, i + 2, 0, memo));
} else {
// buy today
best = max(best, -p[i] + go(p, i + 1, 1, memo));
}
return res = best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const n = prices.length;
// memo[holding][i] caches go(i, holding)
const memo = [new Array(n).fill(null), new Array(n).fill(null)];
const go = (i, holding) => {
if (i >= n) return 0;
const h = holding ? 1 : 0;
if (memo[h][i] !== null) return memo[h][i];
let best = go(i + 1, holding); // skip the day
if (holding) {
// sell today, cooldown tomorrow, continue at i + 2
best = Math.max(best, prices[i] + go(i + 2, false));
} else {
// buy today
best = Math.max(best, -prices[i] + go(i + 1, true));
}
memo[h][i] = best;
return best;
};
return go(0, false);
};
GoTested in our runner
func maxProfit(prices []int) int {
n := len(prices)
// memo[i][h]: best profit from day i in state h (0 = not holding, 1 = holding); set marks computed states
memo := make([][2]int, n)
set := make([][2]bool, n)
var run func(i int, h int) int
run = func(i int, h int) int {
if i >= n {
return 0
}
if set[i][h] {
return memo[i][h]
}
// skip the day
best := run(i+1, h)
if h == 1 {
// sell today, cooldown tomorrow, continue at i + 2
if v := prices[i] + run(i+2, 0); v > best {
best = v
}
} else {
// buy today
if v := -prices[i] + run(i+1, 1); v > best {
best = v
}
}
set[i][h] = true
memo[i][h] = best
return best
}
return run(0, 0)
}C#Tested in our runner
using System;
public class Solution {
private int[,] memo;
private bool[,] seen;
public int maxProfit(int[] prices) {
int n = prices.Length;
memo = new int[n + 2, 2];
seen = new bool[n + 2, 2];
return Go(prices, 0, 0);
}
// h = 1 when holding a share; memoized recursion over (day, state)
private int Go(int[] p, int i, int h) {
if (i >= p.Length) return 0;
if (seen[i, h]) return memo[i, h];
int best = Go(p, i + 1, h); // skip the day
if (h == 1) {
// sell today, cooldown tomorrow, continue at i + 2
best = Math.Max(best, p[i] + Go(p, i + 2, 0));
} else {
best = Math.Max(best, -p[i] + Go(p, i + 1, 1));
}
seen[i, h] = true;
memo[i, h] = best;
return best;
}
}Approach 2: Bottom-up DP over days
What's slow: the recursion solves the same question, such as the best profit from day 7 while empty-handed, once for every path that reaches it. There are only 2 * n distinct questions (i, holding), yet the tree has about 2^n calls.
The insight that fixes it: each answer depends only on later days, so compute answers once and store them. Memoizing the recursion works, but with n up to 5000 a recursive version can overflow the stack in Python. Filling two arrays from the last day backward gives the same result with no recursion.
Define free[i] as the best profit from day i onward when you hold nothing and may buy, and hold[i] as the best profit from day i onward when you hold a share. Days past the end contribute 0.
Steps
- Create arrays
freeandholdof length n + 2, filled with 0, so indexesnandn + 1act as the empty future. - Loop
ifromn - 1down to 0. - Set
free[i] = max(free[i + 1], hold[i + 1] - prices[i]): wait, or buy today. - Set
hold[i] = max(hold[i + 1], prices[i] + free[i + 2]): wait, or sell today and skip the cooldown day. - The extra slot at
n + 1makesfree[i + 2]safe on the last day. - Return
free[0].
Dry run
Trace on [1,2,4,2,5,7,2,4,9,0], filling from the back. Entries at 10 and 11 are 0.
| i | price | free[i] | hold[i] |
|---|---|---|---|
| 9 | 0 | 0 | 0 |
| 8 | 9 | 0 | 9 |
| 7 | 4 | 5 | 9 |
| 6 | 2 | 7 | 9 |
| 5 | 7 | 7 | 12 |
| 4 | 5 | 7 | 12 |
| 3 | 2 | 10 | 12 |
| 2 | 4 | 10 | 12 |
| 1 | 2 | 10 | 12 |
| 0 | 1 | 11 | 12 |
At i = 5, hold[5] = 7 + free[7] = 7 + 5 = 12: sell at 7, rest, then trade 4 to 9 for 5 more. At i = 0, free[0] = max(10, 12 - 1) = 11, which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the number of days. The loop runs n times and each iteration does two max operations on stored values, which is constant work, so time is O(n). The two arrays each hold n + 2 numbers, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
# free[i]: best profit from day i on, holding nothing and allowed to buy
# hold[i]: best profit from day i on, holding one share
free = [0] * (n + 2)
hold = [0] * (n + 2)
for i in range(n - 1, -1, -1):
free[i] = max(free[i + 1], hold[i + 1] - prices[i])
# selling today forces a cooldown, so continue from day i + 2
hold[i] = max(hold[i + 1], prices[i] + free[i + 2])
return free[0]
JavaTested in our runner
import java.util.*;
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[] free = new int[n + 2]; // holding nothing, may buy
int[] hold = new int[n + 2]; // holding one share
for (int i = n - 1; i >= 0; i--) {
free[i] = Math.max(free[i + 1], hold[i + 1] - prices[i]);
// selling today forces a cooldown, so continue from day i + 2
hold[i] = Math.max(hold[i + 1], prices[i] + free[i + 2]);
}
return free[0];
}
}
C++Tested in our runner
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<int> freeDay(n + 2, 0); // holding nothing, may buy
vector<int> hold(n + 2, 0); // holding one share
for (int i = n - 1; i >= 0; i--) {
freeDay[i] = std::max(freeDay[i + 1], hold[i + 1] - prices[i]);
// selling today forces a cooldown, so continue from day i + 2
hold[i] = std::max(hold[i + 1], prices[i] + freeDay[i + 2]);
}
return freeDay[0];
}
};
JavaScriptTested in our runner
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const n = prices.length;
const free = new Array(n + 2).fill(0); // holding nothing, may buy
const hold = new Array(n + 2).fill(0); // holding one share
for (let i = n - 1; i >= 0; i--) {
free[i] = Math.max(free[i + 1], hold[i + 1] - prices[i]);
// selling today forces a cooldown, so continue from day i + 2
hold[i] = Math.max(hold[i + 1], prices[i] + free[i + 2]);
}
return free[0];
};
GoTested in our runner
func maxProfit(prices []int) int {
n := len(prices)
larger := func(a, b int) int {
if a > b {
return a
}
return b
}
free := make([]int, n+2) // holding nothing, may buy
hold := make([]int, n+2) // holding one share
for i := n - 1; i >= 0; i-- {
free[i] = larger(free[i+1], hold[i+1]-prices[i])
// selling today forces a cooldown, so continue from day i + 2
hold[i] = larger(hold[i+1], prices[i]+free[i+2])
}
return free[0]
}
C#Tested in our runner
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.Length;
int[] free = new int[n + 2]; // holding nothing, may buy
int[] hold = new int[n + 2]; // holding one share
for (int i = n - 1; i >= 0; i--) {
free[i] = Math.Max(free[i + 1], hold[i + 1] - prices[i]);
// selling today forces a cooldown, so continue from day i + 2
hold[i] = Math.Max(hold[i + 1], prices[i] + free[i + 2]);
}
return free[0];
}
}

Solution pattern
Stock problems
Approach 3: Three-state machine with O(1) spaceOptimalStock problems
What's slow: the arrays hold n values each, yet every entry is read only by the next one or two entries. Most of the stored table is dead weight.
The insight that fixes it: scan forward and keep three numbers for the current day. hold is the best profit ending the day with a share. sold is the best profit ending the day after selling that day. rest is the best profit ending the day empty-handed and free to buy.
The cooldown shows up as a missing edge: you buy only from rest, never from sold. A sale moves you to sold, and the next day sold flows into rest, so the earliest buy is two days after the sale.
Why it is correct. Each state keeps the best profit over every valid plan that ends in that state on that day. What you can do next depends only on the state, not on how you got there, so a lower total in the same state can never win later. Any future moves that work for a lower total also work for a higher one, so discarding the lower plans loses no answer.
Steps
- Initialise for day 0:
hold = -prices[0],sold = 0,rest = 0. - For each later day, copy the three values from yesterday before changing any of them.
- Update
hold = max(prevHold, prevRest - price): keep the share, or buy from a free day. - Update
sold = prevHold + price: the only way to sell is from holding. - Update
rest = max(prevRest, prevSold): keep resting, or finish the cooldown. - After the last day, return
max(sold, rest). Ending with a share in hand is never better than selling it.
Dry run
Trace on [1,2,4,2,5,7,2,4,9,0]. Day 0 starts at hold -1, sold 0, rest 0. The sold value of 0 on day 0 is harmless, because it only feeds rest, which is already 0.
| Day | Price | hold | sold | rest |
|---|---|---|---|---|
| 0 | 1 | -1 | 0 | 0 |
| 1 | 2 | -1 | 1 | 0 |
| 2 | 4 | -1 | 3 | 1 |
| 3 | 2 | -1 | 1 | 3 |
| 4 | 5 | -1 | 4 | 3 |
| 5 | 7 | -1 | 6 | 4 |
| 6 | 2 | 2 | 1 | 6 |
| 7 | 4 | 2 | 6 | 6 |
| 8 | 9 | 2 | 11 | 6 |
| 9 | 0 | 6 | 2 | 11 |
On day 6, hold = max(-1, 4 - 2) = 2, using rest from day 5, which is 4 because the day-5 sale was already one day old. On day 8, sold = 2 + 9 = 11. On day 9, rest = max(6, 11) = 11, the cooldown after that sale. The answer is max(sold, rest) = max(2, 11) = 11.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the number of days. The loop visits each price once and does a fixed number of additions and max operations, so time is O(n). Only the three variables and three temporary copies are stored. That count does not depend on n, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# hold: end the day with a share
# sold: end the day having just sold (tomorrow is a cooldown)
# rest: end the day empty-handed and free to buy
hold = -prices[0]
sold = 0
rest = 0
for price in prices[1:]:
prev_hold, prev_sold, prev_rest = hold, sold, rest
hold = max(prev_hold, prev_rest - price) # buy only from rest
sold = prev_hold + price # sell from holding
rest = max(prev_rest, prev_sold) # cooldown ends
return max(sold, rest)
JavaTested in our runner
import java.util.*;
class Solution {
public int maxProfit(int[] prices) {
// hold: end the day with a share
// sold: end the day having just sold
// rest: end the day empty-handed and free to buy
int hold = -prices[0];
int sold = 0;
int rest = 0;
for (int i = 1; i < prices.length; i++) {
int prevHold = hold, prevSold = sold, prevRest = rest;
hold = Math.max(prevHold, prevRest - prices[i]); // buy only from rest
sold = prevHold + prices[i]; // sell from holding
rest = Math.max(prevRest, prevSold); // cooldown ends
}
return Math.max(sold, rest);
}
}
C++Tested in our runner
class Solution {
public:
int maxProfit(vector<int>& prices) {
// hold: end the day with a share
// sold: end the day having just sold
// rest: end the day empty-handed and free to buy
int hold = -prices[0];
int sold = 0;
int rest = 0;
for (size_t i = 1; i < prices.size(); i++) {
int prevHold = hold, prevSold = sold, prevRest = rest;
hold = std::max(prevHold, prevRest - prices[i]); // buy only from rest
sold = prevHold + prices[i]; // sell from holding
rest = std::max(prevRest, prevSold); // cooldown ends
}
return std::max(sold, rest);
}
};
JavaScriptTested in our runner
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
// hold: end the day with a share
// sold: end the day having just sold
// rest: end the day empty-handed and free to buy
let hold = -prices[0];
let sold = 0;
let rest = 0;
for (let i = 1; i < prices.length; i++) {
const prevHold = hold, prevSold = sold, prevRest = rest;
hold = Math.max(prevHold, prevRest - prices[i]); // buy only from rest
sold = prevHold + prices[i]; // sell from holding
rest = Math.max(prevRest, prevSold); // cooldown ends
}
return Math.max(sold, rest);
};
GoTested in our runner
func maxProfit(prices []int) int {
larger := func(a, b int) int {
if a > b {
return a
}
return b
}
// hold: end the day with a share
// sold: end the day having just sold
// rest: end the day empty-handed and free to buy
hold := -prices[0]
sold := 0
rest := 0
for i := 1; i < len(prices); i++ {
prevHold, prevSold, prevRest := hold, sold, rest
hold = larger(prevHold, prevRest-prices[i]) // buy only from rest
sold = prevHold + prices[i] // sell from holding
rest = larger(prevRest, prevSold) // cooldown ends
}
return larger(sold, rest)
}
C#Tested in our runner
public class Solution {
public int maxProfit(int[] prices) {
// hold: end the day with a share
// sold: end the day having just sold
// rest: end the day empty-handed and free to buy
int hold = -prices[0];
int sold = 0;
int rest = 0;
for (int i = 1; i < prices.Length; i++) {
int prevHold = hold, prevSold = sold, prevRest = rest;
hold = Math.Max(prevHold, prevRest - prices[i]); // buy only from rest
sold = prevHold + prices[i]; // sell from holding
rest = Math.Max(prevRest, prevSold); // cooldown ends
}
return Math.Max(sold, rest);
}
}
Common mistakes
- Buying from the sold state:
hold = max(prevHold, prevSold - price). That lets you buy the day after a sale, which the cooldown forbids. Buy only fromrest, and letsoldflow intorestfirst. - Overwriting a state and then reading it in the same day:
hold = ...; sold = hold + price. The second line now uses today'shold, so you can buy and sell on one day. Copy yesterday's values intoprevHold,prevSoldandprevRestbefore any update. - Starting with
hold = 0. That treats the first share as free and inflates the profit. Start withhold = -prices[0], since buying on day 0 costs the price. - Returning
max(hold, sold, rest). A day ending with a share in hand has not realised its profit, andholdcan look large only through bookkeeping. Returnmax(sold, rest). - Using only two states, held and not held. Not held hides whether you may buy tomorrow, so the cooldown cannot be enforced. Split it into
soldandrest. - In the recursion, selling and then calling
go(i + 1, false). That allows a buy on the cooldown day. After a sale, jump togo(i + 2, false).
Edge cases
[1]: a single day gives 0, because you cannot sell after buying on the same day.[5, 4, 3, 2, 1]: prices only fall, so the best plan is no trades and the answer is 0.[1, 2]: buy then sell gives 1, and the cooldown never matters.[1, 2, 3, 0, 2]: the answer is 3. Buy 1, sell 2, rest, buy 0, sell 2 gives 1 + 2, which beats buying at 1 and selling at 3 for 2.[2, 2, 2, 2]: flat prices give 0, since every trade has zero profit.pricesof length 5000 with alternating 0 and 1000: the answer stays well within a 32-bit int, and the O(n) solutions run instantly while the plain recursion would not finish.
Follow-ups interviewers ask
- How would you add a transaction fee, as in LeetCode 714, in place of the cooldown?
- Drop the
soldstate and use two states,holdandfree. Subtract the fee when you sell:free = max(free, hold + price - fee)andhold = max(hold, free - price), with the oldfreeandholdused on the right. The cooldown needed a third state only because of the one-day lag. - What if the cooldown were k days instead of one?
- Sold profits must wait k days before they count as free to buy. In the array form, use
hold[i] = max(hold[i + 1], prices[i] + free[i + k + 1]). That costs O(n) time and O(n) space. You can keep O(k) space by storing only a window of the last k + 1freevalues. The forward version can instead keep a queue of delayed sale profits. - Can you return the actual days to buy and sell, not only the profit?
- Yes. Use the array version and store, for each state, which choice produced the maximum. Walk from day 0 following those choices and record each buy and sell day. This needs the O(n) arrays, because the O(1) rolling version discards the history that backtracking needs.
Best Time to Buy and Sell Stock with Cooldown FAQ
What is the time complexity of Best Time to Buy and Sell Stock with Cooldown?
The state machine and the bottom-up table both run in O(n), where n is the number of days. Each day does a constant number of max operations. The plain recursion is O(2^n) because it re-solves the same day and holding state many times.
Why use dynamic programming for Best Time to Buy and Sell Stock with Cooldown?
The best choice today depends on whether you hold a share and whether you sold yesterday. Those few states repeat across many different histories, so storing the best profit per state avoids the exponential blow-up. A greedy rule such as take every rise fails because it ignores the forced rest day.
Can Best Time to Buy and Sell Stock with Cooldown be solved in O(1) extra space?
Yes. Day i reads only day i - 1, so three variables for hold, sold and rest are enough. You roll them forward one day at a time. You would need O(n) space only if you wanted to rebuild the exact trades.
How do I solve LeetCode 309 in Python?
Set hold = -prices[0], sold = 0, rest = 0. For each later price, compute the new hold, sold and rest from the old values, then return max(sold, rest). Copy the old values first, using tuple assignment such as prev_hold, prev_sold, prev_rest = hold, sold, rest.
Why do I need three states and not two for the cooldown?
Two states cannot tell a day on which you sold from a day on which you rested. Only the second lets you buy tomorrow. Splitting empty-handed into sold and rest encodes the rule that a buy needs a rest day directly before it.
How is LeetCode 309 different from Best Time to Buy and Sell Stock II?
Stock II allows unlimited trades with no waiting, so adding up every positive daily difference is optimal. The cooldown makes some of those greedy trades illegal, so you need the three-state DP. Setting the cooldown to zero days collapses the model back to Stock II.
Asked at
See which companies ask this — Pro
Related problems
- Best Time to Buy and Sell Stock II · same technique: Stock problems
- Best Time to Buy and Sell Stock III · same technique: Stock problems
- Best Time to Buy and Sell Stock IV · same technique: Stock problems
- Best Time to Buy and Sell Stock · same technique: Stock problems
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns
- Edit Distance · same pattern: Dynamic Programming (DP) Patterns
- House Robber · same pattern: Dynamic Programming (DP) Patterns