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.
- 1 <= prices.length <= 10⁵
- 0 <= prices[i] <= 10⁵
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.
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.
Approach
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.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Collecting every rise
profit += max(0, prices[i] - prices[i - 1])
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
runs.sort(reverse=True) return sum(runs[:2])
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
buy1, buy2 = -prices[0], 0
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.
Edge cases
[7, 6, 4, 3, 1]Every sale is below every earlier buy, so sell1 and sell2 stay 0 and no trade is made.
[1, 2, 3, 4, 5]The best plan is a single trade from 1 to 5. sell2 ends equal to sell1, which is 4.
Complexity
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.