Best Time to Buy and Sell Stock III
Hard
Topics
Given an array prices where prices[i] is the stock price on day i, return the maximum profit you can achieve with at most two transactions. You may not hold more than one share at a time (you must sell before you buy again).
Example 1
Input: prices = [3,3,5,0,0,3,1,4] Output: 6
Example 2
Input: prices = [1,2,3,4,5] Output: 4
Example 3
Input: prices = [7,6,4,3,1] Output: 0
Constraints
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
With one transaction allowed this is easy: track the lowest price so far and the best profit against it. With two, the obvious extension is to pick a split point — do the best single transaction in prices[0..i] and the best in prices[i..n-1], then maximise over i. Computing both halves with prefix and suffix scans makes that O(n) time and O(n) space, and it is a perfectly good answer worth offering.
The sharper framing drops the split point entirely. Instead of asking "where do I divide the timeline", ask "what state am I in". At any moment the trader is in exactly one of four:
buy1— holding the first stocksell1— sold once, holding nothingbuy2— holding the second stocksell2— sold twice, done
Each state's best value is reachable only from the previous one, so each day we update four numbers:
buy1 = max(buy1, -price) start fresh
sell1 = max(sell1, buy1 + price) close the first
buy2 = max(buy2, sell1 - price) reinvest what the first earned
sell2 = max(sell2, buy2 + price) close the secondThese are profits, not prices, which is why buying is -price: it is money out. buy2 = sell1 - price is the line that carries the whole idea — the capital available for the second purchase is whatever the first transaction netted.
The detail that surprises people is that updating all four in order, within the same day, is correct. It looks like it permits buying and selling the same stock on the same day, because sell1 has already been updated when buy2 reads it. It does, and that is harmless: a same-day buy and sell contributes exactly zero profit, so it can never beat a real pair. Allowing the degenerate case costs nothing and removes the need to stage the updates.
Approach
- Initialise
buy1 = buy2 = -infinityandsell1 = sell2 = 0. The sell states start at 0 because doing nothing is always available; the buy states start at -infinity so they cannot be chosen before any price is seen. - For each price, update the four in the order above.
- Return
sell2. It already covers using fewer than two transactions, sincesell2can inherit fromsell1through a zero-profit second trade.
Dry Run
prices = [3,3,5,0,0,3,1,4], expected 6 (buy at 0, sell at 3, buy at 1, sell at 4).
price buy1 sell1 buy2 sell2
3 -3 0 -3 0
3 -3 0 -3 0
5 -3 2 -3 2 first transaction 3 -> 5
0 0 2 2 2 buy1 improves to 0; buy2 = sell1 - 0 = 2
0 0 2 2 2
3 0 3 2 5 sell2 = buy2 + 3 = 5
1 0 3 2 5
4 0 4 2 6 sell2 = buy2 + 4 = 6
answer 6Watch row 4. The price drops to 0 and buy2 jumps to 2, meaning "I have banked 2 from the first trade and paid nothing for the second stock". That stored 2 is what makes the final answer 6 rather than 4 — the two transactions are never explicitly identified, only their combined profit.
Complexity
- Time — O(n): one pass, four constant-time updates per day. Same as the prefix/suffix split-point method.
- Space — O(1): four numbers, and this is the gain over the split-point approach, which needs two O(n) arrays. It also generalises: the same pattern with
2kstates solves the "at most k transactions" variant in O(nk) time and O(k) space, which is the natural follow-up.
Common Pitfalls
- Initialising the buy states to 0 instead of -infinity. Zero implies a stock was acquired for free, which inflates the answer on a strictly rising input.
- Updating the four in the wrong order.
buy2must readsell1after it has been updated for the day; reversing them loses a transaction's worth of profit. - Worrying about the same-day buy/sell that the in-order update permits. It yields zero profit and can never win, so no guard is needed — but say so rather than leaving it looking like a bug.
- Returning
max(sell1, sell2). Unnecessary:sell2can always absorb a zero-profit second trade, so it already dominatessell1. - Trying to reconstruct which days were traded from these four numbers. They are maxima, not a path; recovering the actual days needs the split-point formulation or extra bookkeeping.
- Assuming the transactions may overlap. They may not — the second buy must come after the first sell, which is exactly what the chain of states enforces.
Full Solution — all languages
class Solution:
def maxProfit(self, nums):
buy1 = buy2 = float('-inf')
sell1 = sell2 = 0
for p in nums:
buy1 = max(buy1, -p)
sell1 = max(sell1, buy1 + p)
buy2 = max(buy2, sell1 - p)
sell2 = max(sell2, buy2 + p)
return sell2import java.util.*;
class Solution {
public int maxProfit(int[] nums) {
long buy1 = -1000000000L, sell1 = 0, buy2 = -1000000000L, sell2 = 0;
for (int p : nums) {
buy1 = Math.max(buy1, (long)-p);
sell1 = Math.max(sell1, buy1 + p);
buy2 = Math.max(buy2, sell1 - p);
sell2 = Math.max(sell2, buy2 + p);
}
return (int)sell2;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxProfit(vector<int>& nums) {
long long buy1 = -1000000000LL, sell1 = 0, buy2 = -1000000000LL, sell2 = 0;
for (int p : nums) {
buy1 = max(buy1, (long long)-p);
sell1 = max(sell1, buy1 + p);
buy2 = max(buy2, sell1 - p);
sell2 = max(sell2, buy2 + p);
}
return (int)sell2;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxProfit = function(nums) {
let buy1 = -Infinity, sell1 = 0, buy2 = -Infinity, sell2 = 0;
for (const p of nums) {
buy1 = Math.max(buy1, -p);
sell1 = Math.max(sell1, buy1 + p);
buy2 = Math.max(buy2, sell1 - p);
sell2 = Math.max(sell2, buy2 + p);
}
return sell2;
};