Start learning free

LESSON 528 OF 673 · DYNAMIC PROGRAMMING

Best Time to Buy and Sell Stock with Cooldown in Python: O(n) DP

Practice O(n) Read the full explanation

You get a list prices. prices[i] is what one share costs on day i.

Return the most profit you can make by buying and selling.

Each day you can buy one share, sell your share, or do nothing. You can hold only one share at a time. You can buy and sell as many times as you like.

After a sale you must rest for one day. So you can't buy on the day right after you sell.

 

Example 1:

Input: prices = [3, 5, 1, 4]
Output: 3
Explanation: Buy at 1 on day 2.
Sell at 4 on day 3.
That earns 4 - 1 = 3.
Buying at 3 and selling at 5 earns only 2.
After that sale, day 2 is a rest day.
So the share at 1 could not be bought.

Example 2:

Input: prices = [2, 6, 5, 1, 7]
Output: 10
Explanation: Buy at 2 on day 0 and sell at 6 on day 1.
That earns 4.
Day 2 is the rest day.
Buy at 1 on day 3 and sell at 7 on day 4.
That earns 6.
In total, 4 + 6 = 10.

Example 3:

Input: prices = [9, 7, 4]
Output: 0
Explanation: The price only goes down.
Every sale would lose money.
So the best plan is to never buy.

 

Constraints:

  • 1 to 5,000 days.
  • Each price is a whole number from 0 to 1,000.

Note:

Your solution should run in O(n) time and use O(1) extra space.



Trying every plan of buys and sells is far too slow. Go day by day instead. At the end of a day you are in one of three states:
  • holding: you own a share;
  • sold: you sold your share today;
  • resting: you own nothing and did not sell today.
Keep the best profit for each state. A purchase counts as minus its price.

Each state comes from yesterday's states:
  • sold: sell today the share you held yesterday;
  • holding: keep yesterday's share, or buy today after a resting day;
  • resting: rest again, or rest the day after a sale.
A purchase never starts from sold. That is the rest day. The answer is the better of sold and resting on the last day.

Each day takes a few steps: O(n) time. Only three running numbers are kept: O(1) extra space.
STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    Best Time To Buy And Sell Stock With Cooldown in Python, explained

    Problem overview

    The method maxProfit receives a list prices, where prices[i] is the cost of one share on day i. Each day you can buy one share, sell the share you hold, or do nothing. You can hold only one share at a time and you can trade as many times as you like. After a sale you must rest for one day, so you can't buy on the day right after you sell. The method returns the most profit possible. There are 1 to 5,000 days and prices are whole numbers from 0 to 1,000.

    For [3, 5, 1, 4] the answer is 3: buy at 1 on day 2 and sell at 4 on day 3. Buying at 3 and selling at 5 earns only 2, and then day 2 would be the rest day, so the share priced 1 couldn't be bought. For [2, 6, 5, 1, 7] the answer is 10: buy at 2 and sell at 6 (4), rest on day 2, then buy at 1 and sell at 7 (6). For [9, 7, 4] the price only falls, so the best plan is never to buy and the answer is 0.

    The statement asks for O(n) time and O(1) extra space.

    Approach: three states per day

    Trying every plan of buys and sells is far too slow: each day has up to three choices, and the number of plans grows exponentially. Instead, go through the days one by one and keep only what the future needs. At the end of a day you are in exactly one of three states:

    • holding: you own a share.
    • sold: you sold your share today.
    • resting: you own nothing and did not sell today.

    For each state, keep the best profit that ends the day in it. A purchase counts as minus its price, and a sale adds the sale price back, so the profit of a finished trade is the sum of both.

    Each state comes from yesterday's states:

    • sold comes from selling today the share held yesterday: holding + prices[i].
    • holding is either yesterday's share kept, or a share bought today after a resting day: resting - prices[i]. It is never bought from sold, because the day after a sale is the rest day.
    • resting is a rest after a rest, or the rest day that follows a sale: the larger of yesterday's resting and yesterday's sold.

    The answer is the better of sold and resting on the last day. Ending with an unsold share can't be best, since you paid for it and never got the money back.

    Step by step

    1. Start day 0. The only way to own a share is to buy it, so holding = -prices[0].
    2. Set sold = 0. No sale can happen on day 0. The 0 does no harm because it equals the resting profit.
    3. Set resting = 0. Doing nothing earns nothing. Only a resting day lets you buy on the next day.
    4. Loop over the other days: for i in range(1, len(prices)). Day 0 is already in the three totals.
    5. Save prevSold = sold. The next lines change sold, and the update of resting at the end of the loop still needs yesterday's value.
    6. Update sold: holding + prices[i]. The right side still uses yesterday's holding because holding changes on the next line.
    7. Update holding: max(holding, resting - prices[i]). Here resting is also yesterday's value, since it is updated last.
    8. Update resting: max(resting, prevSold).
    9. Return max(sold, resting).

    The order of steps 5 to 8 matters: each update must read yesterday's numbers, and a variable is overwritten only after the updates that need its old value have run.

    The solution in Python

    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            holding = -prices[0]
            sold = 0
            resting = 0
            for i in range(1, len(prices)):
                prevSold = sold
                sold = holding + prices[i]
                holding = max(holding, resting - prices[i])
                resting = max(resting, prevSold)
            return max(sold, resting)
    

    Python details worth noting:

    • range(1, len(prices)) starts at 1 and stops before len(prices). With one day it is empty, so the loop doesn't run and the method returns max(0, 0), which is 0.
    • max with two arguments returns the larger one. It is a built-in function, so it needs no import.
    • Negative numbers are normal here. holding is minus the price of a share, so it is usually below zero. Python integers don't overflow, so there is no concern about the sizes involved.
    • The same thing in one assignment. A tuple assignment, sold, holding, resting = holding + p, max(holding, resting - p), max(resting, sold), evaluates the whole right side before assigning, which would replace the prevSold variable. The version above keeps each step visible.

    Tracing the examples

    The table shows the three totals at the end of each day for [3, 5, 1, 4]:

    daypriceholdingsoldresting
    03-300
    15-320
    21-1-22
    34-132

    On day 1, sold is 2, the profit of buying at 3 and selling at 5. On day 2 that 2 moves into resting, and holding becomes -1: buying at 1 is allowed because day 2 follows a day when no sale happened. On day 3, selling that share gives -1 + 4 = 3, and max(3, 2) is the answer, 3.

    For [2, 6, 5, 1, 7]:

    daypriceholdingsoldresting
    02-200
    16-240
    25-234
    313-14
    473104

    On day 3, holding jumps to 3 because resting - 1 = 4 - 1: the profit of the first trade, then a purchase at 1. Selling at 7 on day 4 gives 10.

    Complexity

    Time: O(n). The loop runs n - 1 times and each round does a fixed number of additions and comparisons.

    Space: O(1). Only holding, sold, resting, prevSold and the loop counter are kept, however many days there are. A table with one row per day would also work, but it would need O(n) space.

    Edge cases and common mistakes

    • One day. [5] gives 0: nothing can be sold.
    • A price that only falls. [9, 7, 4] gives 0, because every sale would lose money and doing nothing is allowed.
    • Buying from the sold state. If holding is updated with sold - prices[i] and there is no resting state, the cooldown disappears. [3, 5, 1, 4] then gives 5 instead of 3, by trading 3 to 5 and 1 to 4.
    • Using the new sold for resting. Writing resting = max(resting, sold) after sold was already updated lets a sale today count as a rest today. It gives 5 for [3, 5, 1, 4] as well. That is the reason for prevSold.
    • Ignoring the cooldown altogether. Adding every rise between neighbouring days gives 5 for [3, 5, 1, 4] and 10 for [2, 6, 5, 1, 7]. The second example matches only because its plan already leaves a rest day.
    • Returning holding. An unsold share is a cost with no income. The answer is the better of sold and resting.

    Testing

    • [3, 5, 1, 4] gives 3.
    • [2, 6, 5, 1, 7] gives 10.
    • [9, 7, 4] gives 0.
    • [5] gives 0.
    • [1, 2] gives 1.
    • [1, 2, 3, 0, 2] gives 3.
    • [1, 2, 4] gives 3: buy at 1 and sell at 4 once.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free