STOP 29 · DYNAMIC PROGRAMMING
Stock Trading State Machines
Three states: holding, cooling down, free O(n) time · O(1) space
- Learn first
- Leads to
- No later stop builds on it.
Warm up with this one
LC 121Best Time to Buy and Sell StockStuck? Peek at the approach
Maintain the lowest earlier purchase price, requiring buying before selling and allowing no trade.
Key points
- Name the states you can be in at the end of a day, then list which state yesterday plus which action today reaches each one.
- All of today's values must come from yesterday's, so assign them simultaneously or through temporaries.
- At most k trades adds a k dimension; a fee is charged once per sale (or purchase); a single trade is just tracking the lowest price so far.
Common pitfalls
- Starting the holding state at 0 means you got a share for free on day 0.
- With negative infinity as the start value, hold + p overflows in C++ and Java; use something like MIN / 2.
- With a cooldown you can buy only from the free state, never straight after selling.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
State machine DP · stocks with a cooldown
Prices 1, 2, 3, 0, 2, with a one-day cooldown after selling: what is the best profit?
Try your own input
- Day
- —
- Best profit
- 0
Each day ends in one of three states: holding a share, just sold (cooling down, no buying tomorrow), or free to buy. Each column comes from the previous one only.
InvariantEach day’s three states come only from the previous day’s: hold → cool (sell), free → hold (buy), cool → free (wait a day).
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 121, with it.
Python
def max_profit_cooldown(prices: list[int]) -> int:
"""Unlimited trades, but after selling you must wait one day before buying."""
hold, cool, free = float("-inf"), 0, 0 # profit at the end of a day in each state
for p in prices:
hold, cool, free = (
max(hold, free - p), # keep holding, or buy today (only from free)
hold + p, # sell today
max(free, cool), # rest
)
return max(cool, free)C++
// Unlimited trades, but after selling you must wait one day before buying.
long long maxProfitCooldown(const vector<int>& prices) {
long long hold = LLONG_MIN / 2, cool = 0, free = 0; // profit at day end in each state
for (int p : prices) {
long long h = max(hold, free - p); // keep holding, or buy today (only from free)
long long c = hold + p; // sell today
long long f = max(free, cool); // rest
hold = h, cool = c, free = f;
}
return max(cool, free);
}Java
class Solution {
// Unlimited trades, but after selling you must wait one day before buying.
long maxProfitCooldown(int[] prices) {
long hold = Long.MIN_VALUE / 2, cool = 0, free = 0; // profit at day end in each state
for (int p : prices) {
long h = Math.max(hold, free - p); // keep holding, or buy today (only from free)
long c = hold + p; // sell today
long f = Math.max(free, cool); // rest
hold = h;
cool = c;
free = f;
}
return Math.max(cool, free);
}
}Go
import "math"
// maxProfitCooldown allows unlimited trades, but after selling you must wait
// one day before buying again.
func maxProfitCooldown(prices []int) int {
hold, cool, free := math.MinInt/2, 0, 0 // profit at the end of a day in each state
for _, p := range prices {
// keep holding or buy today (only from free); sell today; rest
hold, cool, free = max(hold, free-p), hold+p, max(free, cool)
}
return max(cool, free)
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
At most k trades: buy[j] and sell[j] statesO(n × k) time · O(k) space
When the number of trades is capped (at most 2, at most k), unfold the state by trade number: buy[j] is the best balance after buying in trade j and sell[j] after completing j trades, updated for each j every day. LC 188 (Best Time to Buy and Sell Stock IV); LC 123 is k = 2.
Python
def max_profit_k(k: int, prices: list[int]) -> int:
"""Best profit with at most k buy-sell pairs, holding one share at a time (LC 188)."""
buy = [float("-inf")] * (k + 1) # buy[j]: best balance while holding in trade j
sell = [0] * (k + 1) # sell[j]: best balance after completing j trades
for p in prices:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - p) # buy today, opening trade j
sell[j] = max(sell[j], buy[j] + p) # sell today, closing trade j
return sell[k]C++
// Best profit with at most k buy-sell pairs, holding one share at a time (LC 188).
int maxProfitK(int k, const vector<int>& prices) {
vector<int> buy(k + 1, INT_MIN / 2), sell(k + 1, 0); // holding in trade j / after completing j trades
for (int p : prices)
for (int j = 1; j <= k; j++) {
buy[j] = max(buy[j], sell[j - 1] - p); // buy today, opening trade j
sell[j] = max(sell[j], buy[j] + p); // sell today, closing trade j
}
return sell[k];
}Java
class Solution {
// Best profit with at most k buy-sell pairs, holding one share at a time (LC 188).
int maxProfitK(int k, int[] prices) {
int[] buy = new int[k + 1], sell = new int[k + 1]; // holding in trade j / after completing j trades
Arrays.fill(buy, Integer.MIN_VALUE / 2);
for (int p : prices)
for (int j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - p); // buy today, opening trade j
sell[j] = Math.max(sell[j], buy[j] + p); // sell today, closing trade j
}
return sell[k];
}
}Go
// maxProfitK returns the best profit with at most k buy-sell pairs, one share at a time (LC 188).
func maxProfitK(k int, prices []int) int {
buy, sell := make([]int, k+1), make([]int, k+1) // holding in trade j / after completing j trades
for j := range buy {
buy[j] = -1 << 60
}
for _, p := range prices {
for j := 1; j <= k; j++ {
buy[j] = max(buy[j], sell[j-1]-p) // buy today, opening trade j
sell[j] = max(sell[j], buy[j]+p) // sell today, closing trade j
}
}
return sell[k]
}Transaction fee: holding and empty statesO(n) time · O(1) space
With unlimited trades and only a fee per trade (or no restriction at all after selling), two states are enough: hold is the best balance with a share in hand, free with none, and selling pays the fee. LC 714 (Best Time to Buy and Sell Stock with Transaction Fee); LC 122 is a fee of 0.
Python
def max_profit_fee(prices: list[int], fee: int) -> int:
"""Unlimited trades, each sale paying fee (LC 714)."""
hold, free = -prices[0], 0 # best balance holding a share / holding none
for p in prices[1:]:
hold, free = max(hold, free - p), max(free, hold + p - fee) # both from yesterday's values
return freeC++
// Unlimited trades, each sale paying fee (LC 714).
int maxProfitFee(const vector<int>& prices, int fee) {
int hold = -prices[0], free = 0; // best balance holding a share / holding none
for (size_t i = 1; i < prices.size(); i++) {
int p = prices[i], held = hold; // both updates read yesterday's values
hold = max(hold, free - p);
free = max(free, held + p - fee);
}
return free;
}Java
class Solution {
// Unlimited trades, each sale paying fee (LC 714).
int maxProfitFee(int[] prices, int fee) {
int hold = -prices[0], free = 0; // best balance holding a share / holding none
for (int i = 1; i < prices.length; i++) {
int p = prices[i], held = hold; // both updates read yesterday's values
hold = Math.max(hold, free - p);
free = Math.max(free, held + p - fee);
}
return free;
}
}Go
// maxProfitFee returns the best profit with unlimited trades, each sale paying fee (LC 714).
func maxProfitFee(prices []int, fee int) int {
hold, free := -prices[0], 0 // best balance holding a share / holding none
for _, p := range prices[1:] {
hold, free = max(hold, free-p), max(free, hold+p-fee) // both from yesterday's values
}
return free
}Why it works
- At the end of each day you are in one of a few states (holding, just sold and cooling down, free to buy); listing which state yesterday plus which action today reaches each one covers every possible trade sequence.
- The cooldown is enforced by allowing buys only from the free state: selling moves you into cooldown, and the next day you can only become free, not buy.
- All three of today's values must come from yesterday's, assigned together or through temporaries; otherwise a sale and a purchase on the same day sneak in.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
股票题我画状态机:每天结束时可能持股、刚卖出处于冷冻期,或者空仓可以买。然后写出每个状态由昨天哪个状态、今天做了什么转移过来,比如持股等于昨天就持股和昨天空仓今天买入两者取大。今天的值都要从昨天的值算,所以同时赋值。最多 k 笔交易就加一维 k,手续费在卖出时扣一次,O(n) 时间、O(1) 空间。For stock problems I draw a state machine: at the end of a day I am holding, cooling down after a sale, or free to buy. Then I write each state from yesterday's states and today's action, for example holding is the better of holding already and buying today from free. All of today's values must come from yesterday's, so I assign them together. At most k trades adds a dimension for k, a fee is subtracted once per sale, and it all runs in O(n) time with O(1) space.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
Practice by stage
This stop's 6 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 1
| # | Problem | Approach | Rating |
|---|---|---|---|
| 121 | Best Time to Buy and Sell Stock | Maintain the lowest earlier purchase price, requiring buying before selling and allowing no trade. |
Core 3
| # | Problem | Approach | Rating |
|---|---|---|---|
| 122 | Best Time to Buy and Sell Stock II | Model repeated trading through holding and not-holding states and explain the equivalence to summing positive gains. | |
| 714 | Best Time to Buy and Sell Stock with Transaction Fee | Charge the fee exactly once per transaction and check whether in-place updates alter the meaning of a state. | |
| 309 | Best Time to Buy and Sell Stock with Cooldown | Model the cooldown explicitly and explain why a sale yesterday cannot transition directly into a purchase today. |
Advanced 2
| # | Problem | Approach | Rating |
|---|---|---|---|
| 123 | Best Time to Buy and Sell Stock III | Add transaction count to the state, distinguishing the funds available for the first and second holdings. | |
| 188 | Best Time to Buy and Sell Stock IV | Generalize to an arbitrary transaction limit, optimizing complexity and handling the large-k case. |