The array prices lists what one share costs on each day: day i costs prices[i]. You may complete at most two trades, where a trade means buying one share and later selling it.
You can hold at most one share at a time, so the first share must be sold before the second is bought. Return the largest total profit you can make. If no trade helps, return 0.
Example 1
Input: prices = [2, 6, 1, 5, 3, 7] Output: 10 Why: buy 2 sell 6, then buy 1 sell 7
2 more examples and the constraints
Example 2
Input: prices = [1, 3, 4, 8] Output: 7 Why: one trade from 1 to 8 is best
Example 3
Input: prices = [9, 6, 5, 2] Output: 0 Why: prices only fall, so do not trade
Constraints
- 1 ≤ length of prices ≤ 100,000
- 0 ≤ each price ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every split dayO(n²)
- Best trade before and afterO(n)
- Four running statesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 days | Verdict |
|---|---|---|---|
| Try every split day | O(n²) | Mention it, then move on | |
| Best trade before and after | O(n) | Passes; two extra arrays | |
| Four running states | O(n) | Best; one pass, four numbers |
n = number of days.
Edge cases to test
- One day. [4] allows no trade; return 0.
- Prices only fall. [9, 6, 5, 2] returns 0, never a loss.
- One trade is best. [1, 3, 4, 8] gives 7. Splitting into two trades cannot beat one long rise.
- Biggest single rise is not part of the answer. [1, 5, 2, 9, 3, 4] gives 4 + 7 = 11, while the single best trade 1 → 9 earns only 8.
Common mistakes
- Taking the two largest single rises, which may overlap in time.
- Starting the buy states at 0, which pretends a share was bought for free.
- Returning sell1 or the max of all states instead of sell2, which already covers doing fewer trades.
How to talk through it
- 1Clarify. At most two trades, never holding two shares at once? Can I sell and buy on the same day?
- 2Give the brute force. Try every split day and solve one trade on each side; O(n²).
- 3Remove the repeats. Precompute the best trade ending by each day and starting from each day: O(n) with two arrays.
- 4Compress to states. Four numbers: buy1, sell1, buy2, sell2. Each day each one stays or advances from the one before.
- 5Test out loud. Run a single day, a falling list, a pure rise and [1, 5, 2, 9, 3, 4].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?