Sub topic 9
Collapsing State into a Small State Machine
This chapter assumes you know bottom-up tabulation and the rolling-variable idea from earlier chapters. It also assumes you can read Python tuple assignment.
Some DP problems seem to need a table indexed by day and by a few extra flags. Often those flags take only a handful of values, and each day's values depend only on the day before. When that holds, you can model the problem as a small state machine. Each state becomes one variable, and the whole table shrinks to a few numbers.
The Problem: Stock Trading with Cooldown
You get a list of daily prices. You may buy and sell as many times as you like, but you hold at most one share at a time. After you sell, you must wait one day before you buy again. The goal is the maximum profit.
A direct table would be dp[day][status]. On any day you are in exactly one of three situations:
| State | Meaning | Reached from (previous day) |
|---|---|---|
| `hold` | You own a share | `hold` (keep it) or `rest` (buy today) |
| `sold` | You sold today | `hold` (sell today) |
| `rest` | You own nothing and may buy | `rest` (wait) or `sold` (cooldown ends) |
Notice that sold can't lead straight to hold. That missing edge is the cooldown rule.
From Table to Three Variables
Each row of dp[day][*] reads only the row for the previous day. That is the same dependency pattern as Fibonacci, applied to a vector of three values. Three variables are enough:
def max_profit_cooldown(prices):
hold, sold, rest = float('-inf'), 0, 0
for p in prices:
hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
return max(sold, rest)
print(max_profit_cooldown([1, 2, 3, 0, 2])) # 3The starting values encode "before day one." You can't already own a share, so hold starts at negative infinity. The answer ignores hold because ending with an unsold share never helps.
Space drops from O(n) to O(1), and time stays O(n).
The Common Error: Updating States One at a Time
The tuple assignment matters. Python evaluates the whole right-hand side using yesterday's values before it assigns anything. If you write the updates on separate lines, later lines read today's values:
hold = max(hold, rest - p)
sold = hold + p # reads today's hold
rest = max(rest, sold) # reads today's soldWith these lines, rest picks up a sale made today, so you can buy again tomorrow with no cooldown. In languages without tuple assignment, copy the old values into temporaries first, then compute the new ones.
Recognizing the Pattern
Look for these signs:
- The extra dimension is a small, fixed set of modes: holding or not, a count of transactions capped at k, or "last action was X."
- Each step reads only the previous step.
- You can draw the allowed moves between modes as a diagram like the one above.
If the number of modes grows with the input, the problem doesn't fit a few variables. The same idea still gives you one array per mode, rolled across steps.
Exercise
Change the problem: there is no cooldown, but each sale costs a fixed fee f. Which states do you need, and what is the update?
Show answer
Two states are enough. cash means you own no share, and hold means you own one. Start with cash = 0 and hold = -inf. Each day, compute both from the previous day's values: hold, cash = max(hold, cash - p), max(cash, hold + p - f). Return cash. The sold state is no longer needed, because no rule depends on having sold on the previous day.
Exercise
Starting from hold = -inf, sold = 0, rest = 0, trace the three variables through prices [1, 2, 3, 0, 2]. On which day does hold first come from rest rather than from the previous hold?
Show answer
The values after each day are: (-1, -inf, 0), (-1, 1, 0), (-1, 2, 1), (1, -1, 2), (1, 3, 2). On day 4 (price 0), hold becomes rest - 0 = 1, which beats the old -1. This is the second buy, and it comes after the day-3 sale and a cooldown. The answer is max(3, 2) = 3.