Best Time to Buy and Sell Stock III (LeetCode 123): Solution and Explanation

Hard
Array
Dynamic Programming

Given daily stock prices, find the largest profit you can make with at most two complete transactions. You must sell before buying again, so the two trades cannot overlap.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A natural brute force splits the days at every index, solves the one-transaction problem on the left part and on the right part, and adds the two results. That is O(n²) if done naively. It can be improved to O(n) with prefix and suffix arrays, but there is a neater one-pass formulation that tracks both transactions at once.

Think of the money you have as you move through the days. For the first trade, the best you can do is buy at the lowest price so far, so buy1 is the minimum price seen, and sell1 is the best profit from selling today against that minimum. That is just the classic single-transaction problem.

The second trade is where the idea pays off. When you buy the second share, you are already carrying the profit from the first trade, so your effective cost is price - sell1. Keeping the minimum of that value in buy2 means the second purchase is discounted by the best first profit available at that point. Then sell2 = max(sell2, price - buy2) is the best total from two trades. Because each variable is updated from values that already account for earlier days, the ordering of trades is respected automatically.

Updating all four variables in the same iteration also covers the case where only one trade is worth making. On a day where buying and selling immediately would occur, the net effect is zero profit, so the formulas gracefully reduce to fewer transactions.

Approach: Four-variable state machine

  1. Initialize buy1 and buy2 to infinity and sell1 and sell2 to 0.
  2. For each price, set buy1 = min(buy1, price), the cheapest first purchase so far.
  3. Set sell1 = max(sell1, price - buy1), the best profit from one trade.
  4. Set buy2 = min(buy2, price - sell1), the cheapest second purchase net of the first profit.
  5. Set sell2 = max(sell2, price - buy2), the best total from two trades.
  6. Return sell2 after processing every price.

Step-by-step example

prices = [3, 3, 5, 0, 0, 3, 1, 4]
  1. After the prices 3 and 3, buy1 = 3, sell1 = 0, buy2 = 3 and sell2 = 0.
  2. Price 5: sell1 = 2, buy2 stays 3 because 5 - 2 = 3, and sell2 = 5 - 3 = 2.
  3. Price 0: buy1 = 0, sell1 stays 2, buy2 = 0 - 2 = -2, meaning the second share is effectively paid for by the first profit. sell2 stays 2.
  4. The second 0 changes nothing. Price 3: sell1 = 3, buy2 stays -2, and sell2 = 3 - (-2) = 5.
  5. Price 1: no improvements. Price 4: sell1 = 4 and sell2 = 4 - (-2) = 6.
  6. The answer is 6, which is buying at 3 and selling at 5, then buying at 0 and selling at 4. The alternative of buying at 0 and selling at 3, then buying at 1 and selling at 4, also gives 6.

Code: Python, Java, C++

1class Solution:
2    def maxProfit(self, prices: List[int]) -> int:
3        buy1 = buy2 = float('inf')
4        sell1 = sell2 = 0
5        for price in prices:
6            buy1 = min(buy1, price)
7            sell1 = max(sell1, price - buy1)
8            buy2 = min(buy2, price - sell1)
9            sell2 = max(sell2, price - buy2)
10        return sell2

Time and space complexity

Time

O(n)

Each price is processed once with four constant-time updates.

Space

O(1)

Only four numbers are maintained no matter how many days there are.

Other approaches

Prefix and suffix split (time O(n), space O(n))

Compute left[i], the best single trade ending by day i, and right[i], the best single trade starting from day i, then take the maximum of left[i] + right[i]. It is very intuitive but needs two extra arrays.

General k-transaction DP (time O(n × k), space O(k))

Use the Stock IV recurrence with k = 2. It handles any k but is more code than this problem needs.

Common mistakes

  • Using price - buy1 in buy2 instead of price - sell1 mixes up costs and profits and gives nonsense values.
  • Initializing buy2 to 0 instead of infinity blocks the second purchase from ever being recorded when the effective cost is positive.
  • Returning sell1 + sell2 double counts the first trade, since sell2 already includes it.
  • Assuming exactly two trades are required; the formulas must also return the single best trade when a second one adds nothing.

Frequently asked questions

How does buy2 = min(buy2, price - sell1) work?

It treats the profit from the first transaction as a discount on the second purchase. The second sell then measures the total profit of both trades, not just the second one.

Does the order of updates matter?

Updating in the order buy1, sell1, buy2, sell2 within the same day is safe. Using today's freshly updated values only allows zero-profit same-day trades, which never increase the answer incorrectly.

What if only one transaction is profitable?

Then sell2 ends up equal to the best single trade, because the second trade can effectively buy and sell on the same day for zero extra profit.

How do you extend this to k transactions?

Replace the four variables with arrays buy[1..k] and sell[1..k] and apply the same pair of updates for each transaction index, which is exactly the Stock IV solution.