State machine DP: stock problems
State machine DP tracks which state you are in on each day, such as holding, sold or cooling down, to solve stock trading problems.
Before you start: Interval DP: matrix chain, burst balloons, palindrome partitioning, Finite automata: DFA and NFA.
The idea
Buy at 1, sell at 2, rest a day, buy at 0, sell at 2: profit 3. How do you find the best plan for any prices?
You hold at most one share. After every sale the next day is a forced rest with no buying.
Intuition
Selling at the peak 3 earns 2, but the cooldown then blocks buying at 0. The best plan sells one day early.
Whether you may buy today depends on what you did yesterday. A value per day alone cannot remember that.
Each day ends in one state: hold a share, just sold, or rest. The arrows are the moves allowed from one day to the next.
Keep one array per state: the best profit if day i ends in that state. Each day reads only the day before.
hold[i] comes from hold or rest yesterday; sold[i] from hold yesterday; rest[i] from rest or sold yesterday. These are exactly the arrows into each state.
Complexity
Three values per day, each from two at most: O(n) time. Yesterday's three values are enough, so space is O(1).
Listing every plan of buy, sell or wait per day grows like 3ⁿ. The states merge all plans that end the day the same way.
Pitfalls
An arrow from sold straight to hold lets you buy the day after a sale. Only rest has a buy arrow.
Starting hold at 0 hands you a free share. On day 0, hold is −price[0], because buying costs money.
Variations
With a fee per sale, two states are enough: hold and cash. The fee comes off each sale; there is no cooldown state.
At most k trades: one buy and one sold state per trade, in a row. The table grows to 2k rows per day.
Code
Pseudocode
maxProfit(prices):
if prices is empty: return 0
hold[0] ← −prices[0]; sold[0] ← −∞; rest[0] ← 0
for i ← 1 to n − 1
hold[i] ← max(hold[i − 1], rest[i − 1] − prices[i])
sold[i] ← hold[i − 1] + prices[i]
rest[i] ← max(rest[i − 1], sold[i − 1])
return max(sold[n − 1], rest[n − 1])
Python
def max_profit(prices):
if not prices:
return 0
hold, sold, rest = -prices[0], float('-inf'), 0
for p in prices[1:]:
new_hold = max(hold, rest - p)
new_sold = hold + p
new_rest = max(rest, sold)
hold, sold, rest = new_hold, new_sold, new_rest
return max(sold, rest)
JavaScript
function maxProfit(prices) {
if (prices.length === 0) return 0;
let hold = -prices[0], sold = -Infinity, rest = 0;
for (let i = 1; i < prices.length; i++) {
const p = prices[i];
const newHold = Math.max(hold, rest - p);
const newSold = hold + p;
const newRest = Math.max(rest, sold);
hold = newHold; sold = newSold; rest = newRest;
}
return Math.max(sold, rest);
}
Java
static int maxProfit(int[] prices) {
if (prices.length == 0) return 0;
long hold = -prices[0], sold = Long.MIN_VALUE / 2, rest = 0;
for (int i = 1; i < prices.length; i++) {
long p = prices[i];
long newHold = Math.max(hold, rest - p);
long newSold = hold + p;
long newRest = Math.max(rest, sold);
hold = newHold; sold = newSold; rest = newRest;
}
return (int) Math.max(sold, rest);
}
Practice problems (5)
Fill the hold, sold and rest arrays Warm-up
Prices for six days are [2, 1, 4, 5, 2, 9]. After a sale you must rest one day. Follow the three state arrays and answer each question before the step plays.
Best time to buy and sell once Warm-up
prices[i] is the price of a stock on day i. Buy one share on one day and sell it on a later day.
Return the largest profit. If no trade makes money, return 0.
Buy and sell with cooldown Standard
prices[i] is the price of a stock on day i. Make as many trades as you like, holding at most one share at a time. After you sell, you cannot buy on the next day.
Return the largest total profit.
Buy and sell with a transaction fee Standard
prices[i] is the price of a stock on day i. Make as many trades as you like, holding at most one share at a time. Every sale costs fee.
Return the largest total profit.
At most k transactions Standard
prices[i] is the price of a stock on day i. Make at most k trades (a buy followed by a later sale), holding at most one share at a time.
Return the largest total profit.
Related topics
Next on the path: Bitmask DP: TSP and assignments