The Runtime Theory
mediumleetcode#dynamic-programming#state-machine

Best Time to Buy and Sell Stock with Cooldown

Maximize profit buying and selling one stock share with a mandatory one-day cooldown after selling; three-state dynamic programming walks the prices once.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

inprices = [1,2,3,0,2]

out3

inprices = [1]

out0

Given a daily price array for a single stock share, the machine must maximize profit with three rules: buy before selling, hold at most one share, and after selling it must wait one full day before buying again. Each day it decides to buy, sell, or do nothing.

The key insight is that the cooldown forces a three-state machine instead of the usual two. The states are hold (cash while owning a share), sold (cash right after selling, blocked from buying tomorrow), and rest (cooldown day or still idle). Each day the machine transitions between these states and keeps the best cash value in each.

The approach runs in three steps. First, initialize hold to negative infinity (you cannot own a share before the first day), and sold and rest to 0. Second, walk the prices once, updating all three states simultaneously: hold from rest minus price, sold from the previous hold plus price, and rest as the best of rest or the previous sold. Third, return the best of sold and rest. Time is O(n) and space is O(1).

The trickiest edge case is a price series too short for a single trade: with one day of prices the machine must return 0, and the initial negative-infinity hold prevents it from ever selling a share it never bought.

python
def maxProfit(prices):
    hold, sold, rest = float("-inf"), 0, 0
    for price in prices:
        hold, sold, rest = (
            max(hold, rest - price),
            hold + price,
            max(rest, sold),
        )
    return max(sold, rest)

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.