Skip to contentKEEP THE CRAFTTHE SANCTUARY

State-machine DP

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.

1 practice exercise3 interview problems

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

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.

Step Executed statement State Why
1 rest=0; hold=float("-inf"); sold=float("-inf") rest=0; hold=-inf; sold=-inf There is no share or sale before the first price.
2 rest=max(previous_rest,previous_sold); hold=max(previous_hold,previous_rest-price); sold=previous_hold+price price=2; [rest,hold,sold]=[0,-2,-inf] Buying is possible from rest, but selling an initially absent share is impossible.
3 rest=max(previous_rest,previous_sold); hold=max(previous_hold,previous_rest-price); sold=previous_hold+price price=4; [rest,hold,sold]=[0,-2,2] A share bought at 2 can sell for profit 2.
4 previous_rest,previous_hold,previous_sold=rest,hold,sold before price 1: previous_rest=0; previous_hold=-2; previous_sold=2 The sold cash is saved separately from cash allowed to buy today.
5 rest=max(previous_rest,previous_sold); hold=max(previous_hold,previous_rest-price); sold=previous_hold+price price=1; [rest,hold,sold]=[2,-1,-1] Rest receives 2, but hold uses previous rest 0, not the just-received sale.
6 sold=previous_hold+price; trace.append([rest,hold,sold]) price=5; [rest,hold,sold]=[2,-1,4] The independent history buying at 1 can sell at 5 for profit 4.
Print Output
print(stock_state_trace([2,4,1,5])) [[0, -2, -inf], [0, -2, 2], [2, -1, -1], [2, -1, 4]]

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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Optimize one-share trading with a one-day cooldownO(n)O(n)Each price causes a constant number of transitions among three modes.

Space

O(1) working state for profit; stock_state_trace adds O(n) output.

Assumptions

  • Initial rest=0 is reachable; initial hold and sold are impossible and use negative infinity.
  • Empty prices yield profit zero and an empty trace.
  • Python tuple assignment snapshots previous values before subsequent assignments; float negative infinity represents impossible modes in these Labs.

Invariants Worth Saying Aloud

  1. hold is the best wealth ending today with one share.
  2. sold is the best cash after selling today, so tomorrow cannot buy from it directly.
  3. rest is the best cash ending today without holding or selling today; it can buy on the following day.
  4. Every transition reads only the three previous-day values.

When To Use Or Avoid State-machine DP

Use It When

  • A fixed small state vector covers all legal histories and transitions depend only on the previous step.
  • Mode meanings can encode exactly when the next action becomes legal.

Choose Another Tool When

  • A mode omits history that affects legality, such as remaining trades or a longer cooldown.
  • A greedy shortcut has not been proved for the action constraints.
  • Different problem variants require different transitions; a fee-only two-state model does not encode this cooldown.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Initializing an owned share for free

A zero hold before any purchase permits positive profit from the first sale.

Prevent it: Initialize impossible ownership to negative infinity.

Avoid

hold=0
sold=hold+price

Use instead

hold=float("-inf")
sold=hold+price

Buying with the just-updated rest value

New rest may contain yesterday's sale, whose proceeds must spend today cooling down.

Prevent it: Read the saved previous rest in the buy transition.

Avoid

rest=max(previous_rest,previous_sold)
hold=max(previous_hold,rest-price)

Use instead

rest=max(previous_rest,previous_sold)
hold=max(previous_hold,previous_rest-price)

Discarding a completed sale when entering rest

After its cooldown day, a sold history is a legal resting history and may finance later trades.

Prevent it: Let rest inherit the better of previous rest and previous sold.

Avoid

rest=previous_rest

Use instead

rest=max(previous_rest,previous_sold)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.