LeetCode #309 Medium

Best Time to Buy and Sell Stock with Cooldown

Best Time to Buy and Sell Stock with Cooldown is LeetCode 309 (Medium). You get an array prices, where prices[i] is the price of one share on day i. Return the maximum profit you can make.

  • You may trade as often as you like, but you can own at most one share at a time, so you sell before you buy again.
  • The day after any sale is a cooldown day: you cannot buy on it.
  • Never trading is allowed, so the answer is at least 0.

There are at most 5000 days, so one pass that carries a few numbers per day is all the work needed.

Constraints
  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000
dynamic-programmingarraystate-machine
Open on LeetCode ↗
02

Intuition

Without the cooldown you could collect every price rise. With it, selling today blocks tomorrow's buy, so grabbing a small rise can cost a bigger one right after it. What you may do today depends on what you did yesterday.

So keep, for each day, the best profit of every situation you can end that day in:

  • hold: you own a share.
  • sold: you sold today, so tomorrow you may not buy.
  • rest: you own nothing and are free to buy tomorrow.

The whole cooldown rule is one missing arrow: a buy can only start from rest, never from sold. Every sale has to pass through one rest day before the next buy.

How to spot this pattern

A rule that depends on your previous action (a rest day, a lockout, a limit on back-to-back moves) means one running total is not enough. Name each situation you can be in at the end of a day, and write which situations can follow which.

03

Approach

Try it first

Take [1, 3, 2, 5]. Collecting both rises gives 5, but one of those buys lands on a cooldown day. Find the real best by hand, then decide which three numbers you would carry from day to day.

1

Set up day 0

Start with hold = -prices[0] (you bought the first share), sold = 0 and rest = 0. Nobody can sell on day 0, but a sold of 0 is harmless: it only ever flows into rest, which is already 0.

2

Sold: sell the share you held yesterday

Save yesterday's sold, then set sold = hold + price. The only way to end a day just after selling is to have held a share the evening before, so there is nothing to compare against.

3

Hold: keep the share or buy one

hold = max(hold, rest - price). You either keep yesterday's share, or you buy today using yesterday's rest profit. Taking money from yesterday's sold instead would mean buying the day after a sale.

4

Rest: wait, or finish the cooldown

rest = max(rest, prev_sold). Either you were already resting, or yesterday you sold and today is the forced rest day. This line needs the sold value from before this day's update, which is why it was saved first.

5

Why three numbers are enough

Every possible trading plan ends each day in exactly one of the three situations, and what it may do next depends only on which one. Keeping the best profit for each situation therefore never throws away a plan that could still win.

6

Return the best state without a share

Answer max(sold, rest). Ending the last day in hold means you paid for a share you never sold, which is always worse than not having bought it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maxProfit(self, prices: List[int]) -> int:
▶3 hold, sold, rest = -prices[0], 0, 0
▶4 for price in prices[1:]:
▶5 prev_sold = sold
▶6 sold = hold + price
▶7 hold = max(hold, rest - price)
▶8 rest = max(rest, prev_sold)
▶9 return max(sold, rest)
price1day 02day 13day 20day 32day 4buysellcooldown dayrest0hold−1sold0day 0: buy at 1 or do nothing
hold−1bought on day 0
sold0
rest0
Three situations. At the end of any day you either own a share (hold), sold one today (sold), or own nothing and may buy tomorrow (rest). Day 0 only allows buying, so hold is −1 and the other two are 0.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest0hold−1sold1sell the held share at 2 → sold 1
day1price 2
sold1hold −1 + 2
Selling today needs a share from last night, so sold is yesterday's hold (−1) plus today's 2. There is no other way into this state, so nothing is compared.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest0hold−1sold1keep the share: hold stays −1
keep−1
buy−2rest 0 − 2
hold−1
Keeping the old share (−1) is at least as good as buying now from rest (−2). The price 2 is too high to be worth a fresh buy.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest0hold−1sold1keep waiting: rest stays 0
wait0
after sale0yesterday's sold
rest0
Coming out of yesterday's sale (0) is no better than having rested all along (0), so rest keeps its value.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest0hold−1sold2sell the held share at 3 → sold 2
day2price 3
sold2hold −1 + 3
Selling today needs a share from last night, so sold is yesterday's hold (−1) plus today's 3. There is no other way into this state, so nothing is compared.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest0hold−1sold2keep the share: hold stays −1
keep−1
buy−3rest 0 − 3
hold−1
Keeping the old share (−1) is at least as good as buying now from rest (−3). The price 3 is too high to be worth a fresh buy.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest1hold−1sold2yesterday's sale cools down → rest 1
wait0
after sale1yesterday's sold
rest1
Yesterday's sale (1) spends today as its cooldown day and arrives in rest, which is better than the old rest (0). From tomorrow this profit may buy again.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest1hold−1sold−1sell the held share at 0 → sold −1
day3price 0
sold−1hold −1 + 0
Selling today needs a share from last night, so sold is yesterday's hold (−1) plus today's 0. There is no other way into this state, so nothing is compared.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest1hold1sold−1buy at 0 from rest → hold 1
keep−1
buy1rest 1 − 0
hold1
Buying today from yesterday's rest (1 − 0 = 1) beats keeping the old share (−1). The buy arrow leaves rest only: yesterday's sold cannot buy, because today is its cooldown day.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest2hold1sold−1yesterday's sale cools down → rest 2
wait1
after sale2yesterday's sold
rest2
Yesterday's sale (2) spends today as its cooldown day and arrives in rest, which is better than the old rest (1). From tomorrow this profit may buy again.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest2hold1sold3sell the held share at 2 → sold 3
day4price 2
sold3hold 1 + 2
Selling today needs a share from last night, so sold is yesterday's hold (1) plus today's 2. There is no other way into this state, so nothing is compared.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest2hold1sold3keep the share: hold stays 1
keep1
buy0rest 2 − 2
hold1
Keeping the old share (1) is at least as good as buying now from rest (0). The price 2 is too high to be worth a fresh buy.
price1day 02day 13day 20day 32day 4buysellcooldown dayrest2hold1sold3keep waiting: rest stays 2
wait2
after sale−1yesterday's sold
rest2
Coming out of yesterday's sale (−1) is no better than having rested all along (2), so rest keeps its value.
price1day 0buy2day 1sell3day 2cool0day 3buy2day 4sellplanbuysellcooldown dayrest2hold1sold3answer: 3
sold3
rest2
answer3
Answer 3. The best of sold and rest on the last day. Walking the states backwards gives the plan in the price row: 2 trades, with the forced rest day between them. Collecting every rise would claim 4, but that plan buys on a cooldown day.
05

Common pitfalls

Summing every rise as if there were no cooldown

✗ Wrong
for i in range(1, len(prices)):
    profit += max(0, prices[i] - prices[i - 1])
✓ Right
hold = max(hold, rest - price)

On [1, 3, 2, 5] the sum of rises is 5: sell at 3 on day 1, buy at 2 on day 2. Day 2 is the cooldown day, so that buy is illegal. The real best is 4, one trade from 1 to 5.

Buying out of yesterday's sale

✗ Wrong
hold = max(hold, max(rest, prev_sold) - price)
✓ Right
hold = max(hold, rest - price)

Letting hold read sold allows a buy the very next day. On [1, 2, 1, 2] that returns 2 (two back-to-back trades), but after selling on day 1 you cannot buy on day 2, so the answer is 1.

Letting rest read today's sale

✗ Wrong
sold = hold + price
hold = max(hold, rest - price)
rest = max(rest, sold)
✓ Right
prev_sold = sold
sold = hold + price
hold = max(hold, rest - price)
rest = max(rest, prev_sold)

With today's sold in it, rest counts the sale day as the rest day, and tomorrow's buy skips the cooldown. On [2, 5, 1, 4] this gives 6 instead of 3.

06

Edge cases

A single day, e.g. [5]

The loop never runs; sold and rest are both 0, so the answer is 0.

Prices that only fall, e.g. [3, 2, 1]

Every sale is below its buy price, so sold stays negative and rest stays 0. Doing nothing wins.

07

Complexity

Time
O(n)
Space
O(1)
One pass over the days. Each day updates three numbers and keeps one saved copy, so no table is built.
08

Best Time to Buy and Sell Stock with Cooldown FAQ

How is this different from Best Time to Buy and Sell Stock II?

Problem 122 has no rest day, so every rise can be collected and two states (holding, not holding) are enough. Here a sale blocks the next day, so "not holding" splits into sold and rest, and only rest may buy.

Can I solve it with recursion and memoization instead?

Yes. Let best(i, holding) either skip day i or trade on it, and make a sale jump to day i + 2 so the cooldown day is skipped. It is also O(n), but with 5000 days Python's default recursion limit of 1000 is too low, so the loop is the safer choice.

Does the cooldown also block selling?

No. Only buying is blocked, and only on the single day right after a sale. You may hold a share through as many days as you like and sell on any of them.