Best Time to Buy and Sell Stock III (LeetCode 123): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Initialize
buy1andbuy2to infinity andsell1andsell2to 0. - For each price, set
buy1 = min(buy1, price), the cheapest first purchase so far. - Set
sell1 = max(sell1, price - buy1), the best profit from one trade. - Set
buy2 = min(buy2, price - sell1), the cheapest second purchase net of the first profit. - Set
sell2 = max(sell2, price - buy2), the best total from two trades. - Return
sell2after processing every price.
Step-by-step example
prices = [3, 3, 5, 0, 0, 3, 1, 4]
- After the prices 3 and 3,
buy1 = 3,sell1 = 0,buy2 = 3andsell2 = 0. - Price 5:
sell1 = 2,buy2stays 3 because 5 - 2 = 3, andsell2 = 5 - 3 = 2. - Price 0:
buy1 = 0,sell1stays 2,buy2 = 0 - 2 = -2, meaning the second share is effectively paid for by the first profit.sell2stays 2. - The second 0 changes nothing. Price 3:
sell1 = 3,buy2stays -2, andsell2 = 3 - (-2) = 5. - Price 1: no improvements. Price 4:
sell1 = 4andsell2 = 4 - (-2) = 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 sell21class Solution {
2 public int maxProfit(int[] prices) {
3 int buy1 = Integer.MAX_VALUE, buy2 = Integer.MAX_VALUE;
4 int sell1 = 0, sell2 = 0;
5 for (int price : prices) {
6 buy1 = Math.min(buy1, price);
7 sell1 = Math.max(sell1, price - buy1);
8 buy2 = Math.min(buy2, price - sell1);
9 sell2 = Math.max(sell2, price - buy2);
10 }
11 return sell2;
12 }
13}1class Solution {
2public:
3 int maxProfit(vector<int>& prices) {
4 int buy1 = INT_MAX, buy2 = INT_MAX;
5 int sell1 = 0, sell2 = 0;
6 for (int price : prices) {
7 buy1 = min(buy1, price);
8 sell1 = max(sell1, price - buy1);
9 buy2 = min(buy2, price - sell1);
10 sell2 = max(sell2, price - buy2);
11 }
12 return sell2;
13 }
14};Time and space complexity
O(n)
Each price is processed once with four constant-time updates.
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 - buy1inbuy2instead ofprice - sell1mixes up costs and profits and gives nonsense values. - Initializing
buy2to 0 instead of infinity blocks the second purchase from ever being recorded when the effective cost is positive. - Returning
sell1 + sell2double counts the first trade, sincesell2already 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.