Sub topic 9
Collapsing State into a Small State Machine
This chapter assumes you are comfortable with bottom-up tabulation, with rolling variables for one-dimensional recurrences, and with tuple assignment in Python (a, b = b, a + b). It also builds on the previous chapter's idea that a state dimension can sometimes be removed.
Some DP problems look like they need a table indexed by day and by "situation". The situations might be holding a stock, being in a cooldown, or having used up a transaction. When the set of situations is small and fixed, each day's row is just a handful of numbers. You can model those situations as states in a finite state machine. Each state becomes one variable, and the whole table shrinks to a few scalars that you update once per step.
The Pattern: A Tiny Fixed Set of Modes
A state machine DP has three ingredients:
- A sequence you scan once, such as days, characters, or positions.
- A small set of modes the process can be in after each step. Only the current mode affects what you may do next.
- Transitions between modes, each with a gain or cost.
The table version stores dp[i][mode], the best value after step i when you end in mode. Each row reads only the previous row, so the step index can be rolled away, as in earlier chapters. The state machine view adds something: it gives you a disciplined way to find the modes in the first place. Once you see the problem as a diagram, the recurrence follows directly from the diagram's arrows.
Memory falls from O(n · s) to O(s), where s is the number of modes. When s is a constant such as 2, 3, or 4, that means O(1).
Worked Example: Stock Trading with Cooldown
You are given daily prices. You may buy and sell one share as many times as you like, holding at most one share at a time. After selling, you must skip the next day before buying again. The goal is maximum profit.
The future depends only on which of these modes you are in at the end of a day:
- hold: you own a share.
- sold: you sold today, so tomorrow you cannot buy.
- rest: you own nothing and did not sell today, so you are free to buy tomorrow.
Each state's new value is the best over all arrows that enter it:
| State today | Incoming arrows | Update |
|---|---|---|
| hold | hold (wait), rest (buy) | `max(hold, rest - p)` |
| sold | hold (sell) | `hold + p` |
| rest | rest (wait), sold (cooldown) | `max(rest, sold)` |
Notice that sold has no arrow into hold. That missing arrow is the cooldown rule. The diagram encodes the constraint structurally, so the recurrence needs no special case for it.
The table version
Writing the table first makes the dependency pattern visible.
def max_profit_cooldown_table(prices):
n = len(prices)
NEG = float('-inf')
hold = [NEG] * (n + 1)
sold = [0] * (n + 1)
rest = [0] * (n + 1)
for i in range(1, n + 1):
p = prices[i - 1]
hold[i] = max(hold[i - 1], rest[i - 1] - p)
sold[i] = hold[i - 1] + p
rest[i] = max(rest[i - 1], sold[i - 1])
return max(sold[n], rest[n])
print(max_profit_cooldown_table([1, 2, 3, 0, 2])) # 3Every right-hand side reads index i - 1 only. Row i depends on row i - 1 and nothing older, so three scalars are enough.
The compressed version
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])) # 3Tracing [1, 2, 3, 0, 2] shows the machine at work:
| Price | hold | sold | rest |
|---|---|---|---|
| start | -inf | 0 | 0 |
| 1 | -1 | -inf | 0 |
| 2 | -1 | 1 | 0 |
| 3 | -1 | 2 | 1 |
| 0 | 1 | -1 | 2 |
| 2 | 1 | 3 | 2 |
The answer is max(3, 2) = 3: buy at 1, sell at 2, cool down on day 3, buy at 0, sell at 2.
Initialization
The starting values describe "before day one":
hold = -infbecause you cannot own a share before you have bought one. Using0would mean you own a free share.rest = 0because doing nothing earns nothing.sold = 0is harmless here, because the only arrow out of sold goes to rest, andmax(0, 0)is still0. Setting it to-infwould also work and is arguably more precise.
The final answer excludes hold, since ending with an unsold share can never beat having sold it or never having bought it.
The Most Common Bug: Sequential Updates
The tuple assignment is what makes the code correct. All right-hand sides are evaluated using the old values before any variable changes. Here is the version people often write first:
def max_profit_cooldown_buggy(prices):
hold, sold, rest = float('-inf'), 0, 0
for p in prices:
hold = max(hold, rest - p)
sold = hold + p # reads today's hold
rest = max(rest, sold) # reads today's sold
return max(sold, rest)
print(max_profit_cooldown_buggy([1, 2, 3, 0, 2])) # 4, wrongThe bug returns 4, which is the answer without a cooldown. rest reads the sold value from the same day. That creates an arrow from sold to rest within a single day, so the next day can buy right after a sale. In table terms, the code reads sold[i] where the recurrence says sold[i - 1].
Sometimes reading a freshly updated value is harmless. In the buggy code, sold = hold + p with the new hold only adds the option of buying and selling on the same day, which earns zero. You should not rely on that kind of luck. Check every same-step read against the diagram.
Verifying Against Brute Force
State machines are easy to get subtly wrong, so test them against an exhaustive search on small inputs.
import random
from functools import lru_cache
def brute_force(prices):
n = len(prices)
@lru_cache(maxsize=None)
def go(i, holding, cooling):
if i == n:
return 0
best = go(i + 1, holding, False) # do nothing today
if holding:
best = max(best, prices[i] + go(i + 1, False, True))
elif not cooling:
best = max(best, -prices[i] + go(i + 1, True, False))
return best
return go(0, False, False)
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)
for _ in range(2000):
prices = [random.randint(0, 9) for _ in range(random.randint(0, 9))]
assert max_profit_cooldown(prices) == brute_force(prices), prices
print("all tests passed")The brute force uses (holding, cooling) as its mode, which is the same information as the three states encoded differently. Both are valid machines. The DP version is cheaper in memory because it keeps only the current step.
A General Recipe
- Ask what the future needs to know. List the facts about the past that change which actions are allowed or what they are worth. Ignore everything else.
- Name the modes. Each combination of those facts that can occur becomes a state.
- Draw the arrows. For one step, list every legal move from each state and its gain or cost.
- Write one update per state. The new value is the max (or min, or sum for counting problems) over incoming arrows.
- Update simultaneously. All updates read the old values.
- Set initial values. Unreachable states start at
-inffor maximization orinffor minimization.
The same recipe covers many variants:
| Variant | States | Space |
|---|---|---|
| Unlimited trades | hold, free | O(1) |
| Transaction fee | hold, free (fee on sell) | O(1) |
| Cooldown | hold, sold, rest | O(1) |
| At most k trades | buy_1, sell_1, ..., buy_k, sell_k | O(k) |
| String matching with a DFA | one per automaton state | O(automaton size) |
When the Pattern Does Not Fit
A state machine collapse needs two things. The transitions must look back exactly one step, and the mode set must be small. If a rule says "you cannot buy within 3 days of a sale", either add states (sold-1-day-ago, sold-2-days-ago) or keep the last few steps with modulo indexing. If the mode would have to record which items you have used, the set of states is exponential, and you need bitmask encoding instead. That is the subject of the next chapter.
Exercise
Adapt the machine for unlimited trades with no cooldown but a fixed fee charged on each sale. How many states do you need, and what are the updates?
Show answer
Two states are enough: hold and free. Use hold, free = max(hold, free - p), max(free, hold + p - fee), starting from hold = -inf and free = 0, and return free. There is no cooldown, so selling moves straight into a state that may buy again, and the sold and rest states merge into one.
Exercise
In the cooldown solution, suppose rest is updated sequentially after sold, but hold and sold are still updated simultaneously. Which constraint breaks, and what does the code return for [1, 2, 3, 0, 2]?
Show answer
The cooldown breaks. rest reads the sold value from the same day, so you can buy on the day after a sale. The code returns 4, which is the answer without a cooldown.
Exercise
Design the states for "at most 2 transactions, no cooldown". Write the four simultaneous updates.
Show answer
The states are b1, s1, b2, s2, the best profit after the first buy, first sell, second buy, and second sell. Use b1, s1, b2, s2 = max(b1, -p), max(s1, b1 + p), max(b2, s1 - p), max(s2, b2 + p), starting from b1 = b2 = -inf and s1 = s2 = 0, and return s2. Because s2 can always equal s1, the answer also covers using zero or one transaction.