Best Time to Buy and Sell Stock with Cooldown
mediumTests passed 2026-11-11v1.0.01. Core Invariant / The Trick
Three-state machine on day `i`: `hold` (currently holding share), `sold` (just sold today -> enters cooldown tomorrow), `rest` (not holding, cooled off). Transitions: `hold = max(hold, rest - p)`, `rest = max(rest, sold)`, `sold = prev_hold + p`.
2. Complexity Bounds & Proof
State-machine FSM reduces 2D `(day, state)` DP table into 3 rolling integer registers.
3. Minimal Idiomatic Code
def maxProfit(prices: list[int]) -> int:
hold, sold, rest = float('-inf'), 0, 0
for p in prices:
prev_hold = hold
hold = max(hold, rest - p)
rest = max(rest, sold)
sold = prev_hold + p
return max(sold, rest)4. Failure Modes & Interview Follow-ups
Pitfalls:- Allowing `rest - p` to transition directly from `sold` skips the mandatory 1-day cooldown.
- Initialize `hold = -inf, sold = 0, rest = 0` so selling before buying is impossible.
Follow-ups:- Stock with Transaction Fee drops `sold` state and subtracts `fee` on sell; Stock IV limits to `k` transactions (`O(N * k)` states).
Personal Notes & Scratchpad (Local-First Yjs CRDT)
Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.
Related Invariants
Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.