15% off all plans & roadmaps Use code

See plans

Best Time to Buy and Sell Stock with Cooldown

Updated

TL;DR: You may buy and sell a stock many times, but you must rest one day after every sale. Track the best profit in three states (holding, sold today, free to buy) and update them once per day in O(n) time and O(1) space.

Problem

You are given an array prices, where prices[i] is the price of a stock on day i.

Find the maximum profit you can make. You may complete as many transactions as you like (buy one share, then sell one share, repeatedly), with this restriction: after you sell, you cannot buy on the very next day. That next day is a cooldown day.

You may not hold more than one share at a time. You must sell the share you own before you buy again.

Example 1

Input: prices = [1,2,3,0,2]
Output: 3
Explanation: the transactions are buy, sell, cooldown, buy, sell.

Example 2

Input: prices = [1]
Output: 0

Constraints

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

Constraints that matter

  • prices.length up to 5000 rules out the exponential recursion, which branches on every day, and allows any O(n) or even O(n^2) method.
  • Only one extra day of lag matters (the cooldown), so each day depends on the previous day or two days back. That is why three running numbers are enough and no full table is required.
  • prices[i] is at most 1000 and n is at most 5000, so the profit is at most about 5,000,000. A 32-bit integer cannot overflow.
  • prices.length >= 1 means you never handle an empty array, but a single price must return 0 because you cannot sell after buying on the same day.
  • Prices are non-negative, so holding a share has a cost of at most 1000 and negative profits only appear in the holding state, never in the final answer.

View on LeetCode

Hints

Hint 1

This is a dynamic programming problem on a stock timeline, usually called a state machine DP.

Hint 2

Try every legal sequence of actions.

Solution

Intuition

This is a dynamic programming problem on a stock timeline, usually called a state machine DP. Each day you choose to buy, sell or wait, and the choice you may make depends on what you did earlier. That dependence is the hint to define a small set of states and track the best profit for each.

Picture three labeled jars on a shelf, each holding the best profit so far for one state, and each day you pour from yesterday's jars into today's. The rest jar only gets filled from the sold jar, so a buy can never pour straight out of sold, which is the cooldown.

Without the cooldown, two states are enough: holding a share or not. The cooldown breaks that. Being empty-handed after a sale is different from being empty-handed after a rest day, because only the second lets you buy tomorrow. So you split the empty-handed state in two, which gives three states: hold, sold (you sold today), and rest (empty-handed and free to buy).

The transitions follow directly. You can only buy from rest. You can only sell from hold. After sold, you must move to rest the next day.

Each state keeps the maximum profit over all ways to reach it. Every valid plan is covered, and every invalid plan (buying right after a sale) is impossible by construction.

Because day i reads only from day i - 1, you never need a table. Three variables rolled forward each day give O(n) time and O(1) space.

Watch the pattern animation

Worked example

Input: prices = [1, 2, 4, 2, 5, 7, 2, 4, 9, 0]
Output: 11
Explanation: Buy on day 0 at 1 and sell on day 5 at 7 for a profit of 6. Rest on day 6. Buy on day 7 at 4 and sell on day 8 at 9 for a profit of 5. The total is 6 + 5 = 11.

Approach 1: Brute force recursion

Try every legal sequence of actions. At day i, you either hold a share or you do not. If you do not hold, you may skip the day or buy. If you hold, you may skip the day or sell, and a sale sends you to day i + 2 because day i + 1 is the cooldown.

The cooldown is handled by jumping two days ahead after a sale, so you need no third flag. The answer is the best total over all paths.

Steps

  1. Define go(i, holding) as the best profit obtainable from day i onward in the given holding state.
  2. If i is past the last day, return 0.
  3. Start with the skip option: go(i + 1, holding).
  4. If holding, try selling: prices[i] + go(i + 2, false). The jump to i + 2 skips the cooldown day.
  5. If not holding, try buying: -prices[i] + go(i + 1, true).
  6. Return the larger option and call go(0, false).

Dry run

Trace on [1,2,4,2,5,7,2,4,9,0]. The call go(0, false) branches into skip (go(1, false)) and buy (-1 + go(1, true)). Each of those branches again, so the tree has about 2^n leaves.

One path in the tree is: buy on day 0 (-1), skip days 1 to 4, sell on day 5 (+7), jump to day 7, buy (-4), sell on day 8 (+9), jump to day 10, return 0. That path totals -1 + 7 - 4 + 9 = 11.

No other path beats it, so the maximum over all branches is 11. The same pair (i, holding) such as (7, false) is reached again and again by different earlier choices, which is the wasted work.

Complexity

TimeO(2^n)
SpaceO(n)

Here n is the number of days. Each call makes up to two recursive calls and the depth can reach n, so the call tree can hold on the order of 2^n nodes. The only memory used is the call stack, which is at most n frames deep.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        # free[i] = go(i, False), hold[i] = go(i, True); the recursion memoized bottom-up
        free = [0] * (n + 2)
        hold = [0] * (n + 2)
        for i in range(n - 1, -1, -1):
            # skip or buy
            free[i] = max(free[i + 1], -prices[i] + hold[i + 1])
            # skip or sell (cooldown: continue at i + 2)
            hold[i] = max(hold[i + 1], prices[i] + free[i + 2])
        return free[0]

Approach 2: Bottom-up DP over days

What's slow: the recursion solves the same question, such as the best profit from day 7 while empty-handed, once for every path that reaches it. There are only 2 * n distinct questions (i, holding), yet the tree has about 2^n calls.

The insight that fixes it: each answer depends only on later days, so compute answers once and store them. Memoizing the recursion works, but with n up to 5000 a recursive version can overflow the stack in Python. Filling two arrays from the last day backward gives the same result with no recursion.

Define free[i] as the best profit from day i onward when you hold nothing and may buy, and hold[i] as the best profit from day i onward when you hold a share. Days past the end contribute 0.

Steps

  1. Create arrays free and hold of length n + 2, filled with 0, so indexes n and n + 1 act as the empty future.
  2. Loop i from n - 1 down to 0.
  3. Set free[i] = max(free[i + 1], hold[i + 1] - prices[i]): wait, or buy today.
  4. Set hold[i] = max(hold[i + 1], prices[i] + free[i + 2]): wait, or sell today and skip the cooldown day.
  5. The extra slot at n + 1 makes free[i + 2] safe on the last day.
  6. Return free[0].

Dry run

Trace on [1,2,4,2,5,7,2,4,9,0], filling from the back. Entries at 10 and 11 are 0.

ipricefree[i]hold[i]
9000
8909
7459
6279
57712
45712
321012
241012
121012
011112

At i = 5, hold[5] = 7 + free[7] = 7 + 5 = 12: sell at 7, rest, then trade 4 to 9 for 5 more. At i = 0, free[0] = max(10, 12 - 1) = 11, which matches the expected output.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of days. The loop runs n times and each iteration does two max operations on stored values, which is constant work, so time is O(n). The two arrays each hold n + 2 numbers, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        # free[i]: best profit from day i on, holding nothing and allowed to buy
        # hold[i]: best profit from day i on, holding one share
        free = [0] * (n + 2)
        hold = [0] * (n + 2)
        for i in range(n - 1, -1, -1):
            free[i] = max(free[i + 1], hold[i + 1] - prices[i])
            # selling today forces a cooldown, so continue from day i + 2
            hold[i] = max(hold[i + 1], prices[i] + free[i + 2])
        return free[0]
Stock problems pattern infographic for Best Time to Buy and Sell Stock with Cooldown

Solution pattern

Stock problems

Part of Dynamic Programming (DP) Patterns

Approach 3: Three-state machine with O(1) spaceOptimalStock problems

What's slow: the arrays hold n values each, yet every entry is read only by the next one or two entries. Most of the stored table is dead weight.

The insight that fixes it: scan forward and keep three numbers for the current day. hold is the best profit ending the day with a share. sold is the best profit ending the day after selling that day. rest is the best profit ending the day empty-handed and free to buy.

The cooldown shows up as a missing edge: you buy only from rest, never from sold. A sale moves you to sold, and the next day sold flows into rest, so the earliest buy is two days after the sale.

Why it is correct. Each state keeps the best profit over every valid plan that ends in that state on that day. What you can do next depends only on the state, not on how you got there, so a lower total in the same state can never win later. Any future moves that work for a lower total also work for a higher one, so discarding the lower plans loses no answer.

Steps

  1. Initialise for day 0: hold = -prices[0], sold = 0, rest = 0.
  2. For each later day, copy the three values from yesterday before changing any of them.
  3. Update hold = max(prevHold, prevRest - price): keep the share, or buy from a free day.
  4. Update sold = prevHold + price: the only way to sell is from holding.
  5. Update rest = max(prevRest, prevSold): keep resting, or finish the cooldown.
  6. After the last day, return max(sold, rest). Ending with a share in hand is never better than selling it.

Dry run

Trace on [1,2,4,2,5,7,2,4,9,0]. Day 0 starts at hold -1, sold 0, rest 0. The sold value of 0 on day 0 is harmless, because it only feeds rest, which is already 0.

DayPriceholdsoldrest
01-100
12-110
24-131
32-113
45-143
57-164
62216
74266
892116
906211

On day 6, hold = max(-1, 4 - 2) = 2, using rest from day 5, which is 4 because the day-5 sale was already one day old. On day 8, sold = 2 + 9 = 11. On day 9, rest = max(6, 11) = 11, the cooldown after that sale. The answer is max(sold, rest) = max(2, 11) = 11.

Complexity

TimeO(n)
SpaceO(1)

Here n is the number of days. The loop visits each price once and does a fixed number of additions and max operations, so time is O(n). Only the three variables and three temporary copies are stored. That count does not depend on n, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # hold: end the day with a share
        # sold: end the day having just sold (tomorrow is a cooldown)
        # rest: end the day empty-handed and free to buy
        hold = -prices[0]
        sold = 0
        rest = 0
        for price in prices[1:]:
            prev_hold, prev_sold, prev_rest = hold, sold, rest
            hold = max(prev_hold, prev_rest - price)  # buy only from rest
            sold = prev_hold + price                  # sell from holding
            rest = max(prev_rest, prev_sold)          # cooldown ends
        return max(sold, rest)

Common mistakes

  • Buying from the sold state: hold = max(prevHold, prevSold - price). That lets you buy the day after a sale, which the cooldown forbids. Buy only from rest, and let sold flow into rest first.
  • Overwriting a state and then reading it in the same day: hold = ...; sold = hold + price. The second line now uses today's hold, so you can buy and sell on one day. Copy yesterday's values into prevHold, prevSold and prevRest before any update.
  • Starting with hold = 0. That treats the first share as free and inflates the profit. Start with hold = -prices[0], since buying on day 0 costs the price.
  • Returning max(hold, sold, rest). A day ending with a share in hand has not realised its profit, and hold can look large only through bookkeeping. Return max(sold, rest).
  • Using only two states, held and not held. Not held hides whether you may buy tomorrow, so the cooldown cannot be enforced. Split it into sold and rest.
  • In the recursion, selling and then calling go(i + 1, false). That allows a buy on the cooldown day. After a sale, jump to go(i + 2, false).

Edge cases

  • [1]: a single day gives 0, because you cannot sell after buying on the same day.
  • [5, 4, 3, 2, 1]: prices only fall, so the best plan is no trades and the answer is 0.
  • [1, 2]: buy then sell gives 1, and the cooldown never matters.
  • [1, 2, 3, 0, 2]: the answer is 3. Buy 1, sell 2, rest, buy 0, sell 2 gives 1 + 2, which beats buying at 1 and selling at 3 for 2.
  • [2, 2, 2, 2]: flat prices give 0, since every trade has zero profit.
  • prices of length 5000 with alternating 0 and 1000: the answer stays well within a 32-bit int, and the O(n) solutions run instantly while the plain recursion would not finish.

Follow-ups interviewers ask

How would you add a transaction fee, as in LeetCode 714, in place of the cooldown?
Drop the sold state and use two states, hold and free. Subtract the fee when you sell: free = max(free, hold + price - fee) and hold = max(hold, free - price), with the old free and hold used on the right. The cooldown needed a third state only because of the one-day lag.
What if the cooldown were k days instead of one?
Sold profits must wait k days before they count as free to buy. In the array form, use hold[i] = max(hold[i + 1], prices[i] + free[i + k + 1]). That costs O(n) time and O(n) space. You can keep O(k) space by storing only a window of the last k + 1 free values. The forward version can instead keep a queue of delayed sale profits.
Can you return the actual days to buy and sell, not only the profit?
Yes. Use the array version and store, for each state, which choice produced the maximum. Walk from day 0 following those choices and record each buy and sell day. This needs the O(n) arrays, because the O(1) rolling version discards the history that backtracking needs.

Best Time to Buy and Sell Stock with Cooldown FAQ

What is the time complexity of Best Time to Buy and Sell Stock with Cooldown?

The state machine and the bottom-up table both run in O(n), where n is the number of days. Each day does a constant number of max operations. The plain recursion is O(2^n) because it re-solves the same day and holding state many times.

Why use dynamic programming for Best Time to Buy and Sell Stock with Cooldown?

The best choice today depends on whether you hold a share and whether you sold yesterday. Those few states repeat across many different histories, so storing the best profit per state avoids the exponential blow-up. A greedy rule such as take every rise fails because it ignores the forced rest day.

Can Best Time to Buy and Sell Stock with Cooldown be solved in O(1) extra space?

Yes. Day i reads only day i - 1, so three variables for hold, sold and rest are enough. You roll them forward one day at a time. You would need O(n) space only if you wanted to rebuild the exact trades.

How do I solve LeetCode 309 in Python?

Set hold = -prices[0], sold = 0, rest = 0. For each later price, compute the new hold, sold and rest from the old values, then return max(sold, rest). Copy the old values first, using tuple assignment such as prev_hold, prev_sold, prev_rest = hold, sold, rest.

Why do I need three states and not two for the cooldown?

Two states cannot tell a day on which you sold from a day on which you rested. Only the second lets you buy tomorrow. Splitting empty-handed into sold and rest encodes the rule that a buy needs a rest day directly before it.

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

Stock II allows unlimited trades with no waiting, so adding up every positive daily difference is optimal. The cooldown makes some of those greedy trades illegal, so you need the three-state DP. Setting the cooldown to zero days collapses the model back to Stock II.

Asked at

See which companies ask this — Pro

Practise it