Skip to content

Best Time to Buy and Sell Stock with Cooldown

Make the most profit from as many stock trades as you like, resting one day after every sale.

Medium2D Dynamic Programming
Solve on LeetCode

The problem

prices[i] is the price of a stock on day i. You may buy and sell as many times as you like, but you can hold at most one share at a time, and after a sale you must wait one full day before you buy again. Return the largest total profit.

Input prices = [2, 6, 1, 3, 8]

Output 9

Buy at 2, sell at 6, rest on the day priced 1, buy at 3 and sell at 8: 4 + 5 = 9.

Input prices = [5, 4, 3, 2]

Output 0

Prices only fall, so the best plan is to never trade.

Key constraint: There are up to 5,000 days, so trying every set of trades is out, but keeping a few numbers per day is easy.

How to spot the pattern

  • Each day you are in one of a few situations (holding, just sold, free) with rules for moving between them.
  • The best profit for a day depends only on the previous day's best profit in each situation.

The idea

State: for each day, the best profit so far in each of three situations: hold (you own a share), sold (you sold today, so tomorrow is a cooldown) and rest (you own nothing and may buy tomorrow). The transitions are hold = max(hold, rest - p), sold = hold + p and rest = max(rest, sold), all computed from yesterday's values. The answer is the better of sold and rest after the last day, because ending with an unsold share never helps.

Brute force: Try buying, selling or waiting on every day recursively, which takes exponential time.

Step by step

  1. 1Before the first day, set rest = 0 and set hold and sold to minus infinity, since you can't own or have sold anything yet.
  2. 2For each price p, the new hold is max(hold, rest - p): keep holding, or buy today after a free day.
  3. 3The new sold is hold + p and the new rest is max(rest, sold), all three using yesterday's values.
  4. 4After the last day, return max(sold, rest).

See the pattern move

The 2d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # Best profit at the end of a day, in each of three states:
        # hold = you own a share, sold = you sold today (tomorrow is a cooldown),
        # rest = you own nothing and may buy tomorrow.
        hold, sold, rest = float("-inf"), float("-inf"), 0  # before the first day
        for p in prices:
            # all three right-hand sides use yesterday's values
            hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
        return max(sold, rest)

Complexity

Time

O(n)

Space

O(1)

One pass over the days that keeps three numbers.

Watch out for

  • Buying from sold instead of rest: you can only buy once the cooldown day has passed.
  • Updating the three states one after another, so a later one reads today's new value instead of yesterday's.
  • Counting hold in the final answer: ending with an unsold share never helps.

Follow-up questions

What if each sale cost a fee instead of a cooldown?

Drop the sold state and pay the fee when you sell: rest = max(rest, hold + p - fee) and hold = max(hold, rest - p).

What if you could make at most k trades?

Add the trade count to the state: keep a hold and a rest value for each count from 0 to k, which takes O(n * k) time.

In Hinglish

Teen haalat yaad rakho: share haath mein (hold), aaj becha (sold) aur free (rest). Har din teeno ko kal ki values se update karo, aur kharidna sirf rest se hota hai.

Related problems