Dynamic Programming · Pattern 6 of 12
State machine DP: every Buy and Sell Stock problem
Each day you are in a state: holding a share or not (plus how many trades are left, or a cooldown). Write how each state is reached from yesterday's states, and keep one variable per state.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Buy and sell on given days to maximise profit
- Rules about what you may do next: a fee, a cooldown, a limit of k trades
- Your options today depend on what you did before, not just on the day
The template
// Unlimited trades with a fee (fee = 0 is Stock II). States: cash (no share) and hold (one share).
int maxProfitFee(int[] prices, int fee) {
int cash = 0, hold = Integer.MIN_VALUE / 2; // you cannot hold a share before day 0
for (int p : prices) {
int newCash = Math.max(cash, hold + p - fee); // rest, or sell today
hold = Math.max(hold, cash - p); // rest, or buy today
cash = newCash;
}
return cash;
}
// Cooldown: after selling you must rest a day, so a buy uses the cash from two days ago
int maxProfitCooldown(int[] prices) {
int cash = 0, prevCash = 0, hold = Integer.MIN_VALUE / 2;
for (int p : prices) {
int newCash = Math.max(cash, hold + p);
hold = Math.max(hold, prevCash - p);
prevCash = cash;
cash = newCash;
}
return cash;
}
// At most k transactions (k = 1 is Stock I, k = 2 is Stock III)
int maxProfitK(int k, int[] prices) {
int[] buy = new int[k + 1], sell = new int[k + 1]; // best after the j-th buy / j-th sell
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);
sell[j] = Math.max(sell[j], buy[j] + p);
}
return sell[k];
} def max_profit_fee(prices, fee): # fee = 0 is Stock II
cash, hold = 0, float('-inf') # no share / one share
for p in prices:
cash, hold = max(cash, hold + p - fee), max(hold, cash - p) # sell today / buy today
return cash
def max_profit_cooldown(prices):
cash, prev_cash, hold = 0, 0, float('-inf')
for p in prices:
# a buy uses the cash from two days ago (yesterday may have been a sale)
cash, prev_cash, hold = max(cash, hold + p), cash, max(hold, prev_cash - p)
return cash
def max_profit_k(k, prices): # k = 1 is Stock I, k = 2 is Stock III
buy = [float('-inf')] * (k + 1) # best after the j-th buy
sell = [0] * (k + 1) # best after the j-th sell
for p in prices:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - p)
sell[j] = max(sell[j], buy[j] + p)
return sell[k] // Unlimited trades with a fee (fee = 0 is Stock II). States: cash (no share) and hold (one share).
int maxProfitFee(vector<int>& prices, int fee) {
int cash = 0, hold = INT_MIN / 2; // you cannot hold a share before day 0
for (int p : prices) {
int newCash = max(cash, hold + p - fee); // rest, or sell today
hold = max(hold, cash - p); // rest, or buy today
cash = newCash;
}
return cash;
}
// Cooldown: a buy uses the cash from two days ago
int maxProfitCooldown(vector<int>& prices) {
int cash = 0, prevCash = 0, hold = INT_MIN / 2;
for (int p : prices) {
int newCash = max(cash, hold + p);
hold = max(hold, prevCash - p);
prevCash = cash;
cash = newCash;
}
return cash;
}
// At most k transactions (k = 1 is Stock I, k = 2 is Stock III)
int maxProfitK(int k, vector<int>& prices) {
vector<int> buy(k + 1, INT_MIN / 2), sell(k + 1, 0); // best after the j-th buy / j-th sell
for (int p : prices)
for (int j = 1; j <= k; j++) {
buy[j] = max(buy[j], sell[j - 1] - p);
sell[j] = max(sell[j], buy[j] + p);
}
return sell[k];
} // Unlimited trades with a fee (fee = 0 is Stock II). States: cash (no share) and hold (one share).
function maxProfitFee(prices, fee) {
let cash = 0, hold = -Infinity;
for (const p of prices) [cash, hold] = [Math.max(cash, hold + p - fee), Math.max(hold, cash - p)];
return cash;
}
// Cooldown: a buy uses the cash from two days ago
function maxProfitCooldown(prices) {
let cash = 0, prevCash = 0, hold = -Infinity;
for (const p of prices)
[cash, prevCash, hold] = [Math.max(cash, hold + p), cash, Math.max(hold, prevCash - p)];
return cash;
}
// At most k transactions (k = 1 is Stock I, k = 2 is Stock III)
function maxProfitK(k, prices) {
const buy = new Array(k + 1).fill(-Infinity), sell = new Array(k + 1).fill(0);
for (const p of prices)
for (let j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - p); // best after the j-th buy
sell[j] = Math.max(sell[j], buy[j] + p); // best after the j-th sell
}
return sell[k];
} The variations
-
1One transaction
Walk the prices and keep the lowest price so far. Selling today earns
price - lowest. It is the k = 1 case of the state machine. -
2Unlimited transactions, with or without a fee
Two states:
cashandhold.cash = max(cash, hold + p - fee),hold = max(hold, cash - p). With no fee this equals adding every rising step.Now you solve -
3Cooldown after selling
A sale blocks tomorrow's buy. Buying today must use the cash from two days ago, so keep one more variable: yesterday's cash.
-
4At most k transactions
One
buy[j]andsell[j]state per transaction number.buy[j]builds onsell[j - 1], so the count of trades is part of the state. Stock III is k = 2. -
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Updating
holdwith thecashvalue you just changed today, which lets you sell and rebuy in a way the rules forbid (it matters for the cooldown). - Starting
holdat 0: you do not own a share before buying one, so it must start at minus infinity. - Charging the fee on both the buy and the sell: it is charged once per transaction.
Lesson done
Next: Knapsack: choose items under a capacity →Mark it done once you can write the template from memory and you have solved the worked examples yourself.