Describe every legal end-of-step mode and keep its best value. Compute all next modes from the previous snapshot; the cooldown Lab needs separate rest, hold and sold states.
Recognize it when The next legal action depends on a small mode such as holding, resting or just sold.
Checking your account…
State-machine DP Code Labs
Let Modes Describe Legal Histories
State-machine DP stores the best value among histories ending in each named condition. The cooldown example has three modes. hold owns one share; sold has sold today; rest owns no share and has not sold today. Separating sold from rest prevents a sale from funding a purchase on the immediately following day.
Draw the Transitions from the Previous Day
To hold today, either keep yesterday’s hold or buy from yesterday’s rest. To sell today, add today’s price to yesterday’s hold. To rest today, keep yesterday’s rest or finish the cooldown after yesterday’s sold. These alternatives cover every legal history for each mode, so taking their maxima preserves optimal values by induction over prices.
Trace Stock State Transitions
Reference
def stock_state_trace(prices):
rest=0;hold=float("-inf");sold=float("-inf");trace=[]
for price in prices:
previous_rest,previous_hold,previous_sold=rest,hold,sold
rest=max(previous_rest,previous_sold);hold=max(previous_hold,previous_rest-price);sold=previous_hold+price
trace.append([rest,hold,sold])
return trace
Practice
Implement stock_state_trace(prices). Return [rest,hold,sold] after each price for one-share trading with one-day cooldown.
Public tests
Read every transition from prior state
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Stock State Transitions
def stock_state_trace(prices):
rest=0;hold=float("-inf");sold=float("-inf");trace=[]
for price in prices:
previous_rest,previous_hold,previous_sold=rest,hold,sold
rest=max(previous_rest,previous_sold);hold=max(previous_hold,previous_rest-price);sold=previous_hold+price
trace.append([rest,hold,sold])
return trace
Keep Sale Proceeds Out of the Next Day’s Buy
Predict stock_state_trace([2,4,1,5]). Rest can receive a prior sale, while buying uses the older rest value saved before that update.
The saved previous vector is essential. Today’s rest may include yesterday’s sold, but that money cannot buy today; using the newly updated rest in the hold expression bypasses the cooldown. Negative infinity prevents impossible initial ownership from generating a free sale.
Accept Only a Completed Nonholding Outcome
The profit Lab uses the same transitions without retaining the trace. Its answer is max(rest,sold), since a held share is not a completed cash outcome. An empty list returns zero. Price order remains unchanged, and the Labs do not mutate the list.
Maximize Stock Profit with Cooldown
Reference
def max_cooldown_profit(prices):
rest=0;hold=float("-inf");sold=float("-inf")
for price in prices:
previous_rest,previous_hold,previous_sold=rest,hold,sold
rest=max(previous_rest,previous_sold);hold=max(previous_hold,previous_rest-price);sold=previous_hold+price
return max(rest,sold)
Practice
Implement max_cooldown_profit(prices). Hold at most one share and wait one day after selling before buying.
Public tests
Respect mutually exclusive states
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Maximize Stock Profit with Cooldown
def max_cooldown_profit(prices):
rest=0;hold=float("-inf");sold=float("-inf")
for price in prices:
previous_rest,previous_hold,previous_sold=rest,hold,sold
rest=max(previous_rest,previous_sold);hold=max(previous_hold,previous_rest-price);sold=previous_hold+price
return max(rest,sold)
Only the previous day is needed, so three entries replace a full daily table. This is O(1) working state under the ordinary bounded-size arithmetic model; the trace separately stores one three-entry vector per price.
Adapt the Mode Model in an Interview
The general pattern extends to any sequence with a small complete set of action modes, but its recurrence follows the actual contract. A transaction fee can use a different two-state model; a trade limit needs another dimension, and a longer cooldown needs more history. Do not transplant those transitions into this Lab. State what each mode allows next, initialize only reachable modes, and explain why all next values use the same previous snapshot before proposing space compression.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
State-machine DP
Name each state; every day, each state takes its best way in from yesterday.
Each day you are in one of a few named situations (holding a share or not, resting after a sale) and actions move you between them.
Trigger words
cooldown
transaction fee
at most k transactions
holding or not
buy and sell many times
def max_profit(prices): # buy and sell as many times as you like
hold = float("-inf") # best profit if you end the day owning a share
cash = 0 # best profit if you end the day owning nothing
for price in prices:
new_hold = max(hold, cash - price) # keep holding, or buy today
new_cash = max(cash, hold + price) # keep waiting, or sell today
hold = new_hold
cash = new_cash
return cash
Spot it when
Stock problems: buy and sell with a fee, a cooldown, or a limit on transactions.
'On each day you may ... or ...'.
Remember
Compute every new state from yesterday's values before overwriting any of them.
Each state is one variable, so the space is O(1) however long the price list is.
How problems bend it
Transaction fee: Subtract the fee when you sell: new_cash = max(cash, hold + price - fee).
One-day cooldown after selling: Add a third state, sold: selling moves hold into sold, sold becomes rest the next day, and you may buy only from rest.
Only one buy and one sell: Buying starts from zero profit: new_hold = max(hold, -price).
Python Version Note
Python 3.11+
Python tuple assignment snapshots previous values before subsequent assignments; float negative infinity represents impossible modes in these Labs.