Best Time to Buy and Sell Stock III

Hard

Topics
ArrayDynamic Programming

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

33500314
At most two transactions, which is what the four running values track: best after one buy, after one sale, after a second buy (funded by the first sale), and after the second sale. Each is updated from the one before it in the same pass, so no split point has to be tried. Maximum profit: 6.
Bars are the daily prices, left to right.
Input:  prices = [3,3,5,0,0,3,1,4]
Output: 6

Example 2

12345
Input:  prices = [1,2,3,4,5]
Output: 4

Example 3

76431
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:

  1. buy1 — holding the first stock
  2. sell1 — sold once, holding nothing
  3. buy2 — holding the second stock
  4. sell2 — 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 second

These 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

  1. Initialise buy1 = buy2 = -infinity and sell1 = 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.
  2. For each price, update the four in the order above.
  3. Return sell2. It already covers using fewer than two transactions, since sell2 can inherit from sell1 through 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 6

Watch 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 2k states 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. buy2 must read sell1 after 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: sell2 can always absorb a zero-profit second trade, so it already dominates sell1.
  • 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 sell2
Asked at Citadel Snap
SensAI
Beta
Tap the mic to stop voice mode