LeetCode #123 Hard

Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III is LeetCode 123 (Hard). You get an array prices, where prices[i] is the price of one share on day i. Return the maximum profit from at most two transactions.

  • A transaction is one buy followed later by one sell.
  • You can own only one share at a time, so the second buy comes after the first sell.
  • Making one trade, or none, is allowed.

There are up to 10⁵ days, so even checking every split of the days into two parts with a fresh scan each time (O(n²)) is too slow.

Constraints
  • 1 <= prices.length <= 10⁵
  • 0 <= prices[i] <= 10⁵
dynamic-programmingarraystate-machine
Open on LeetCode ↗
02

Intuition

Two trades always happen in the same order: buy, sell, buy, sell. Give each point in that order its own running best as you walk the days:

  • buy1: the best balance after the first buy (money spent, so it is negative).
  • sell1: the best profit after the first sell.
  • buy2: the best balance after buying again, with the first trade's profit already in hand.
  • sell2: the best profit after the second sell, which is the answer.

Each stage is fed only by the stage before it. The second trade cannot start before the first one ends, and the limit of two is built into the chain instead of being counted.

How to spot this pattern

A small fixed cap on the number of actions, taken in a fixed order, can become one running number per step of that order. The cap is the length of the chain.

03

Approach

Try it first

Take [3, 5, 0, 3, 1, 4]. It has three rising runs but you may use only two trades. Pick the best two by hand, then ask which single number would tell a second buy how much profit it can start from.

1

Seed both buys with day 0

Set buy1 = buy2 = -prices[0] and sell1 = sell2 = 0. Seeding buy2 this way is a real plan: buy and sell at the same price on day 0, then buy again. A seed of 0 would describe a share that cost nothing.

2

First trade: cheapest buy, best single sale

buy1 = max(buy1, -price) keeps the cheapest buy so far, and sell1 = max(sell1, buy1 + price) keeps the best one-trade profit so far. These two lines alone would solve the one-transaction version.

3

Second buy: start from the first profit

buy2 = max(buy2, sell1 - price) buys today using the profit of a finished first trade. A good second buy is a low price that follows a high first sale, and this one number weighs both at once.

4

Second sell: the answer

sell2 = max(sell2, buy2 + price). Because buy2 may buy on the same day the first trade sells, sell2 is never below sell1, so a plan that needs only one trade is covered without a special case.

5

Why updating in place is safe

Each line reads a value already changed on the same day. That only adds the option of selling and buying back at the same price, which earns 0, so it never creates a profit no real plan could make.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maxProfit(self, prices: List[int]) -> int:
▶3 buy1 = buy2 = -prices[0]
▶4 sell1 = sell2 = 0
▶5 for price in prices[1:]:
▶6 buy1 = max(buy1, -price)
▶7 sell1 = max(sell1, buy1 + price)
▶8 buy2 = max(buy2, sell1 - price)
▶9 sell2 = max(sell2, buy2 + price)
▶10 return sell2
price3day 05day 10day 23day 31day 44day 51st buy−31st sell02nd buy−32nd sell0tryeach day tries all four boxes in orderday 0: both buys start at −3
buy1−3
sell10
buy2−3
sell20
Four stages, one chain. Each box is the best balance after reaching that point of buy, sell, buy, sell. On day 0 the only real move is buying at 3, so both buy boxes start at −3 and nothing has been sold.
price3day 05day 10day 23day 31day 44day 51st buy−31st sell02nd buy−32nd sell0try0−5=−5vs−3kept5 is no cheaper: keep −3
day1price 5
buy1−3kept
An earlier day was at least as cheap, so the first buy stays where it is.
price3day 05day 10day 23day 31day 44day 51st buy−31st sell22nd buy−32nd sell0try−3+5=2vs0replacedsell at 5 → first profit 2
day1price 5
sell12replaced
Selling the first share today gives 2, the best single trade so far. The second buy will be able to spend this profit.
price3day 05day 10day 23day 31day 44day 51st buy−31st sell22nd buy−32nd sell0try2−5=−3vs−3keptbuying again at 5 gives −3: keep −3
day1price 5
buy2−3kept
Paying 5 out of 2 leaves −3, which is not better than the second buy already found (−3).
price3day 05day 10day 23day 31day 44day 51st buy−31st sell22nd buy−32nd sell2try−3+5=2vs0replacedsecond sale at 5 → total 2
day1price 5
sell22replaced
Selling the second share today brings the total to 2. So far that only matches the best single trade.
price3day 05day 10day 23day 31day 44day 51st buy01st sell22nd buy−32nd sell2try0−0=0vs−3replacedcheapest buy so far: 0 → 0
day2price 0
buy10replaced
Buying at 0 costs less than any earlier day, so the first buy moves here. A cheaper first buy can only raise every sale after it.
price3day 05day 10day 23day 31day 44day 51st buy01st sell22nd buy−32nd sell2try0+0=0vs2keptselling at 0 makes 0: keep 2
day2price 0
sell12kept
A first sale today would make 0, no better than the 2 already found.
price3day 05day 10day 23day 31day 44day 51st buy01st sell22nd buy22nd sell2try2−0=2vs−3replacedbuy again at 0 with 2 profit → 2
day2price 0
buy22replaced
The second buy starts from the first trade's profit (2) and pays 0. A low price after a good first sale is exactly what this box looks for.
price3day 05day 10day 23day 31day 44day 51st buy01st sell22nd buy22nd sell2try2+0=2vs2kepta second sale at 0 gives 2: keep 2
day2price 0
sell22kept
Closing the second trade today is not better than the 2 already reached.
price3day 05day 10day 23day 31day 44day 51st buy01st sell22nd buy22nd sell2try0−3=−3vs0kept3 is no cheaper: keep 0
day3price 3
buy10kept
An earlier day was at least as cheap, so the first buy stays where it is.
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell2try0+3=3vs2replacedsell at 3 → first profit 3
day3price 3
sell13replaced
Selling the first share today gives 3, the best single trade so far. The second buy will be able to spend this profit.
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell2try3−3=0vs2keptbuying again at 3 gives 0: keep 2
day3price 3
buy22kept
Paying 3 out of 3 leaves 0, which is not better than the second buy already found (2).
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell5try2+3=5vs2replacedsecond sale at 3 → total 5
day3price 3
sell25replaced
Selling the second share today brings the total to 5. That beats the best single trade (3), so two trades are paying off.
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell5try0−1=−1vs0kept1 is no cheaper: keep 0
day4price 1
buy10kept
An earlier day was at least as cheap, so the first buy stays where it is.
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell5try0+1=1vs3keptselling at 1 makes 1: keep 3
day4price 1
sell13kept
A first sale today would make 1, no better than the 3 already found.
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell5try3−1=2vs2keptbuying again at 1 gives 2: keep 2
day4price 1
buy22kept
Paying 1 out of 3 leaves 2, which is not better than the second buy already found (2).
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell5try2+1=3vs5kepta second sale at 1 gives 3: keep 5
day4price 1
sell25kept
Closing the second trade today is not better than the 5 already reached.
price3day 05day 10day 23day 31day 44day 51st buy01st sell32nd buy22nd sell5try0−4=−4vs0kept4 is no cheaper: keep 0
day5price 4
buy10kept
An earlier day was at least as cheap, so the first buy stays where it is.
price3day 05day 10day 23day 31day 44day 51st buy01st sell42nd buy22nd sell5try0+4=4vs3replacedsell at 4 → first profit 4
day5price 4
sell14replaced
Selling the first share today gives 4, the best single trade so far. The second buy will be able to spend this profit.
price3day 05day 10day 23day 31day 44day 51st buy01st sell42nd buy22nd sell5try4−4=0vs2keptbuying again at 4 gives 0: keep 2
day5price 4
buy22kept
Paying 4 out of 4 leaves 0, which is not better than the second buy already found (2).
price3day 05day 10day 23day 31day 44day 51st buy01st sell42nd buy22nd sell6try2+4=6vs5replacedsecond sale at 4 → total 6
day5price 4
sell26replaced
Selling the second share today brings the total to 6. That beats the best single trade (4), so two trades are paying off.
price3buy 05sell 10buy 23day 31day 44sell 51st buy01st sell42nd buy22nd sell6trades+2++4=6answer: 6
sell26
trades2
Answer 6. The last box holds the best total. The two trades are marked in the price row. Taking every rise would claim 8, but that needs more than two trades.
05

Common pitfalls

Collecting every rise

✗ Wrong
profit += max(0, prices[i] - prices[i - 1])
✓ Right
sell2 = max(sell2, buy2 + price)

That is the unlimited-trades answer. [3, 5, 0, 3, 1, 4] has three rising runs worth 2, 3 and 3, so it returns 8, but with two trades the best is 6: buy at 3, sell at 5, then buy at 0, sell at 4.

Adding the two biggest rising runs

✗ Wrong
runs.sort(reverse=True)
return sum(runs[:2])
✓ Right
buy2 = max(buy2, sell1 - price)

One trade may span a dip. On [1, 2, 4, 2, 5, 7, 2, 4, 9, 0] the runs are worth 3, 5 and 7, so the top two give 12. Buying at 1 and selling at 7 (6), then 2 to 9 (7), gives 13.

Seeding the second buy at 0

✗ Wrong
buy1, buy2 = -prices[0], 0
✓ Right
buy1 = buy2 = -prices[0]

A buy2 of 0 means a second share that cost nothing, so any later price counts as pure profit. On [3, 2] it returns 2, although no trade can make money there.

06

Edge cases

Prices that only fall, e.g. [7, 6, 4, 3, 1]

Every sale is below every earlier buy, so sell1 and sell2 stay 0 and no trade is made.

One long rise, e.g. [1, 2, 3, 4, 5]

The best plan is a single trade from 1 to 5. sell2 ends equal to sell1, which is 4.

07

Complexity

Time
O(n)
Space
O(1)
One loop over the days with four running numbers, one per stage of the two trades.
08

Best Time to Buy and Sell Stock III FAQ

How is this different from Best Time to Buy and Sell Stock IV?

Problem 188 gives the cap k as input, so the four named numbers become two arrays of length k + 1 and the loop costs O(n · k). This page is that problem with k fixed at 2, which is why four variables are enough.

Can I split the days into a first half and a second half instead?

Yes. A left-to-right pass records the best one-trade profit using days up to i, a right-to-left pass the best one using days from i on, and the answer is the largest sum at any split i. It is also O(n), but it needs two arrays of length n.