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:
soldcomes from selling today the share held yesterday:holding + prices[i].holdingis either yesterday's share kept, or a share bought today after a resting day:resting - prices[i]. It is never bought fromsold, because the day after a sale is the rest day.restingis a rest after a rest, or the rest day that follows a sale: the larger of yesterday'srestingand yesterday'ssold.
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
- Start day 0. The only way to own a share is to buy it, so
holding = -prices[0]. - Set
sold = 0. No sale can happen on day 0. The 0 does no harm because it equals the resting profit. - Set
resting = 0. Doing nothing earns nothing. Only a resting day lets you buy on the next day. - Loop over the other days:
for i in range(1, len(prices)). Day 0 is already in the three totals. - Save
prevSold = sold. The next lines changesold, and the update ofrestingat the end of the loop still needs yesterday's value. - Update
sold:holding + prices[i]. The right side still uses yesterday'sholdingbecauseholdingchanges on the next line. - Update
holding:max(holding, resting - prices[i]). Hererestingis also yesterday's value, since it is updated last. - Update
resting:max(resting, prevSold). - 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 beforelen(prices). With one day it is empty, so the loop doesn't run and the method returnsmax(0, 0), which is 0.maxwith two arguments returns the larger one. It is a built-in function, so it needs no import.- Negative numbers are normal here.
holdingis 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 theprevSoldvariable. 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]:
| day | price | holding | sold | resting |
|---|---|---|---|---|
| 0 | 3 | -3 | 0 | 0 |
| 1 | 5 | -3 | 2 | 0 |
| 2 | 1 | -1 | -2 | 2 |
| 3 | 4 | -1 | 3 | 2 |
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]:
| day | price | holding | sold | resting |
|---|---|---|---|---|
| 0 | 2 | -2 | 0 | 0 |
| 1 | 6 | -2 | 4 | 0 |
| 2 | 5 | -2 | 3 | 4 |
| 3 | 1 | 3 | -1 | 4 |
| 4 | 7 | 3 | 10 | 4 |
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
soldstate. Ifholdingis updated withsold - 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
soldforresting. Writingresting = max(resting, sold)aftersoldwas 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 forprevSold. - 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 ofsoldandresting.
Testing
[3, 5, 1, 4]gives3.[2, 6, 5, 1, 7]gives10.[9, 7, 4]gives0.[5]gives0.[1, 2]gives1.[1, 2, 3, 0, 2]gives3.[1, 2, 4]gives3: buy at 1 and sell at 4 once.
