◀ THE GRIND — 2-D DYNAMIC PROGRAMMING

Best Time to Buy And Sell Stock With Cooldown

MEDIUM✓ CHIP-TIMEDLC #309 — FULL STATEMENT ↗

The drill: Buy and sell a single share as many times as you like across these daily prices to maximize profit — but after every sell you must sit out one full day before buying again.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A sequence of daily stock prices arrives, and the task is to buy and sell a single share of stock as many times as helpful to maximize total profit.

Only one share can be held at a time — a new share can't be bought while already holding one, and a sale has to happen before buying again. After any sale, though, a full day of cooldown must pass before the next buy is allowed.

There's no requirement to actually trade; sitting out entirely and taking zero profit is always a valid, if unhelpful, option. The output is the maximum profit reachable under these rules.

EX 01
prices = [7]
0
ONE DAY, NOTHING TO TRADE
EX 02
prices = [4, 9]
5
SINGLE PROFITABLE TRADE
EX 03
prices = [9, 4]
0
PRICE ONLY FALLS
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

At any point you're in exactly one of three situations: holding a share, freshly sold and resting, or free to buy. What determines the best outcome from here in each case?

HINT 2 THE STRUCTURE

Today's 'holding' can only descend from yesterday's 'holding' (do nothing) or yesterday's 'free, no cooldown' (buy today) — it can never come straight from yesterday's 'just sold'.

HINT 3 ONE STEP FROM THE ANSWER

Track three running maxima across the days: hold, sold-today, and rest (free with no cooldown). hold = max(hold, rest − price); sold = hold_prev + price; rest = max(rest, sold_prev). Answer is max(sold, rest) at the end.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE COOLDOWN LEDGERPATTERN · THREE-STATE DPprices = [2, 4, 1, 7]
2
4
1
7
STATE — HOLD / SOLD / REST
hold-2
sold0
rest0
STEP 1

Day0, price2. Buying now costs 2, so hold starts at -2; nothing sold yet, so sold and rest sit at 0.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/best-time-to-buy-and-sell-stock-with-cooldown.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        hold = -prices[0]
        sold = 0
        rest = 0
        for price in prices[1:]:
            hold, sold, rest = max(hold, rest - price), hold + price, max(rest, sold)
        return max(sold, rest)
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 10 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED