Stock DP as a state machine
Picture
On the same day, holding a share and holding none allow different next actions.
Predict
Does buying complete a buy-sell transaction?
Walk through the small example
No, selling completes it here. Legal actions depend on holding state and remaining transaction budget.
Mental model and complete Python solution
Draw two rooms per transaction count: free and holding. Every day offers edges—rest, buy, sell. DP keeps the best money reaching each room.
What the function promises: Return maximum profit from integer prices with at most k transactions. Same-day buy after sell is harmless here but never increases profit without fees.
def max_profit(prices, k):
if k < 0: raise ValueError("Negative k")
free = [0] + [float("-inf")] * k
hold = [float("-inf")] * (k+1)
for price in prices:
old_free, old_hold = free[:], hold[:]
for sold in range(k+1):
hold[sold] = max(old_hold[sold], old_free[sold]-price)
free[sold] = old_free[sold]
if sold:
free[sold] = max(free[sold], old_hold[sold-1]+price)
return max(free)
assert max_profit([3,2,6,5,0,3], 2) == 7
assert max_profit([], 3) == 0
Work and storage: O(nk) time and O(k) space.
When to recognize it: Legal actions depend on holding state and remaining transaction budget.
Check before applying it: Updating states in-place in the wrong order can use today’s sale to buy again under a different contract.
Change one rule
Cooldown is required after selling.
See what changes
Add a cooldown/free distinction or carry a recent-sale state; “not holding” is no longer sufficient.
Connect
dp state: State records exactly what changes legal future actions.
state machine: Transitions are legal actions between named states.