Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — 2-D Dynamic Programming

Best Time to Buy And Sell Stock With Cooldown

MEDIUM✓ CHIP-TIMEDLC #309 — FULL STATEMENT

The briefingthe full drill, in my own words

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.

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.

  • prices are non-negative, and the list can be short or empty
  • at most one share is held at any moment
  • one full day of cooldown is required after every sell before the next buy
  • not trading at all is valid, giving a baseline profit of zero
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 hintstake 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 boardthe pattern, step by step

THE COOLDOWN LEDGERPATTERN · THREE-STATE DPprices = [2, 4, 1, 7]
2
4
1
7
STATE — HOLD / SOLD / REST
hold → -2
sold → 0
rest → 0
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 splitstwo paces, two languages

grind/best-time-to-buy-and-sell-stock-with-cooldown.py — RACE 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-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED