sagelearnai

Best Time to Buy and Sell Stock III

Difficulty: Hard · Pattern: 1-D Dynamic Programming · LeetCode #123

You may complete at most two transactions, and you can't hold more than one share at a time. Return the maximum profit.

Examples

text
[3,3,5,0,0,3,1,4]  →  6    (buy 0 sell 3, buy 1 sell 4)
[1,2,3,4,5]        →  4
[7,6,4,3,1]        →  0

Hints

  1. Extend the hold/cash state machine to count transactions: after the first buy, after the first sell, after the second buy, after the second sell.

Approach

text
b1 = b2 = -inf; s1 = s2 = 0
for p in prices:
    b1 = max(b1, -p)          # first buy
    s1 = max(s1, b1 + p)      # first sell
    b2 = max(b2, s1 - p)      # second buy, funded by the first profit
    s2 = max(s2, b2 + p)      # second sell
return s2

Updating in this order within the same day is safe. It only allows same-day buy-and-sell, which gains nothing. Alternative: prefix best-single-trade from the left plus suffix best from the right, maximizing the sum over a split point. Both are O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def maxProfit(prices):
    b1 = b2 = float('-inf')
    s1 = s2 = 0
    for p in prices:
        b1 = max(b1, -p)
        s1 = max(s1, b1 + p)
        b2 = max(b2, s1 - p)
        s2 = max(s2, b2 + p)
    return s2
JavaScript solution
function maxProfit(prices) {
  let b1 = -Infinity, b2 = -Infinity, s1 = 0, s2 = 0;
  for (const p of prices) {
    b1 = Math.max(b1, -p); s1 = Math.max(s1, b1 + p);
    b2 = Math.max(b2, s1 - p); s2 = Math.max(s2, b2 + p);
  }
  return s2;
}