Best Time to Buy and Sell Stock with Cooldown solution explained

Best Time to Buy and Sell Stock with Cooldown allows unlimited trades but forbids buying on the day right after a sale. Track three values per day: the best profit while holding a share, after selling today, and while resting free to buy. Each day, holding comes from holding or buying out of the rest state, selling comes from holding, and resting comes from resting or from yesterday's sale; the answer is the better of the last two, in O(n) time and O(1) memory.

By Published 7 min read

The problem, restated

Same setup as the unlimited-trades version: daily prices known in advance, buy or sell one share at a time, as many round trips as you like. One new rule: the day after you sell, you may not buy. You may still do nothing that day, and you may buy on any later day. Find the largest total profit.

Examples written for this page
PricesWith cooldownWithout cooldownBest plan with cooldown
[2, 5, 1, 4]36One trade, 2 to 5 or 1 to 4; the dip at 1 falls on the rest day
[3, 1, 6, 2, 8]711Buy 1, hold through the dip, sell 8
[4, 6, 5, 9, 1, 7]8124 to 6, rest, then 1 to 7; skipping the bigger 4 to 9 trade
[1, 4, 2, 7]68Hold from 1 to 7
[9, 8, 7]00Never trade
Examples written for this page. Scroll sideways on a small screen.

The third row is the interesting one. The single biggest trade, 4 to 9, earns 5, but its rest day would land exactly on the cheapest price. Taking the smaller 4 to 6 trade first leaves the rest day on 5 and frees you to buy at 1. No local rule finds that; you need to carry the options forward.

What the interviewer is testing

This is a state machine problem in disguise. The interviewer wants to see you name the states you can be in at the end of a day, list which moves connect them, and turn that into a few variables updated per day. People who try to patch the greedy answer from the unlimited version usually end up with special cases that fail on inputs like the third row above.

Follow-ups

  • Add a fee per trade as well. Subtract the fee in the sold transition; nothing else changes.
  • A cooldown of k days. In the two-array form below, buy from the free value k + 1 days back instead of two.
  • Show the trades. Store the full arrays of states and walk back from the last day, choosing the transition that produced each value.
  • What if the cooldown applied after buying? Same method: move the forced gap to the other edge of the machine.

Brute force

Recurse over days with two flags: whether you hold a share, and whether today is a forced rest day. On each day you either wait or make the one move allowed by the flags. Trying everything is O(2^n), but the recursion has only n times 3 distinct states, which is the hint that a handful of variables per day will do.

def max_profit_cooldown_slow(prices, day=0, holding=False, resting=False):
    if day == len(prices):
        return 0
    best = max_profit_cooldown_slow(prices, day + 1, holding, False)  # wait
    if holding:
        best = max(best, prices[day] + max_profit_cooldown_slow(prices, day + 1, False, True))
    elif not resting:
        best = max(best, -prices[day] + max_profit_cooldown_slow(prices, day + 1, True, False))
    return best
Python: exhaustive search with the rest day enforced.

The state machine

Where each end-of-day state can come from
State at end of todayMeaningReached from yesterday'sValue
holdOwn a sharehold (keep it) or rest (buy today)max(hold, rest - price)
soldSold today, so tomorrow is a rest dayhold (sell today)hold + price
restNo share, free to buy tomorrowrest (do nothing) or sold (the forced rest)max(rest, sold)
Where each end-of-day state can come from. Scroll sideways on a small screen.

Notice the missing arrow: there is no path from sold straight to hold. That is the cooldown. Start with hold at minus infinity (you cannot own a share before day one), sold at minus infinity, and rest at 0. On the last day, holding a share is never best, so the answer is the larger of sold and rest.

def max_profit_cooldown(prices):
    hold, sold, rest = float("-inf"), float("-inf"), 0
    for p in prices:
        hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
    return max(sold, rest)
Python: three values per day, all updated from yesterday's values.
function maxProfitWithCooldown(prices) {
  let hold = -Infinity;
  let sold = -Infinity;
  let rest = 0;
  for (const p of prices) {
    const prevHold = hold;
    const prevSold = sold;
    hold = Math.max(hold, rest - p);
    sold = prevHold + p;
    rest = Math.max(rest, prevSold);
  }
  return Math.max(sold, rest);
}
JavaScript: the same machine. Save yesterday's values before overwriting.

In JavaScript the order of the three lines matters. hold must read rest before rest is updated, and both sold and rest must read yesterday's hold and sold. Python's tuple assignment evaluates the whole right side first, which hides that detail, so mention it if you switch languages mid-interview.

Trace [2, 5, 1, 4]. Day 1: hold -2, sold minus infinity, rest 0. Day 2: hold stays -2, sold 3, rest 0. Day 3: hold max(-2, 0 - 1) = -1, sold -2 + 1 = -1, rest max(0, 3) = 3. Day 4: hold max(-1, 3 - 4) = -1, sold -1 + 4 = 3, rest 3. The answer is 3.

Another way to write it

Some people prefer two arrays: free[i] for the best profit with no share at the end of day i, and hold[i]. A purchase on day i must come from the free value two days back, since the day before might have been a sale. It is the same machine with the rest state folded in.

def max_profit_cooldown_lag(prices):
    free_two_back, free, hold = 0, 0, float("-inf")
    for p in prices:
        new_hold = max(hold, free_two_back - p)
        free_two_back, free = free, max(free, hold + p)
        hold = new_hold
    return free
Python: buy from the free value two days earlier.

Complexity

n days of prices
ApproachTimeExtra memory
Exhaustive searchO(2^n)O(n) stack
Memoized search on (day, holding, resting)O(n)O(n)
Three state valuesO(n)O(1)
Free two days backO(n)O(1)
n days of prices. Scroll sideways on a small screen.

Edge cases

  • Empty list or one day: 0.
  • Two days: either one trade or none; the cooldown cannot matter yet.
  • A dip that lands exactly on the rest day, as in [2, 5, 1, 4].
  • Long rising runs, where one long trade beats several short ones with gaps.

Common mistakes

  • Letting hold come from sold, which skips the cooldown entirely.
  • Updating variables in place in a language without tuple assignment, so one state reads today's value instead of yesterday's.
  • Starting hold at 0, which pretends you got a share for free.
  • Returning max(hold, sold, rest), which can only matter if hold is wrongly initialized.
  • Reusing the greedy sum of rises and trying to subtract something for the gaps.

How to explain it out loud

Fictional example

Naming the states first
Candidate
At the end of any day I am in one of three situations: holding a share, having just sold today, or resting with no share and allowed to buy.
Candidate
Holding comes from holding or from buying out of resting. Just-sold comes only from holding. Resting comes from resting or from yesterday's sale, which is where the cooldown lives: there is no arrow from sold to holding.
Candidate
So I keep three numbers and update them from yesterday's values each day. Linear time, constant memory, and the answer is the better of sold and resting at the end.

Best Time to Buy and Sell Stock II is the version without the rest day, where a greedy sum works. Distinct Subsequences is a counting DP over two strings, a useful contrast to this day-by-day machine. Perfect Squares is another one-dimensional DP, where each value looks back at a small set of earlier ones.

Practicing with Natively

Drawing the three states and their arrows before coding is the habit to build here. In a practice session on Mac or Windows, Natively can read the problem from a screenshot and suggest a state setup to compare with yours once you have tried, and the transcript of your mock round shows whether you explained the missing arrow clearly. Read about the AI interview assistant.

Questions people ask

How do you solve Best Time to Buy and Sell Stock with Cooldown?

Track three values per day: hold = max(hold, rest - price), sold = hold + price, rest = max(rest, sold), all from the previous day's values. Start with hold and sold at minus infinity and rest at 0, and return max(sold, rest).

Why does the stock cooldown problem need three states?

After a sale you are not simply free: the next day you cannot buy. Separating just-sold from resting makes that rule a missing transition, since a purchase may only come from the resting state.

What is the time complexity of the stock with cooldown problem?

O(n) time and O(1) extra memory for n days, because each day updates three numbers.

Why doesn't the greedy sum of rises work with a cooldown?

Back-to-back trades now cost a day, so taking every small rise can block a better purchase later. The best plan may skip a larger trade so the rest day falls on a less useful day.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP