You are given an array
Output: 6
Explanation: Buy on day 4 (price=0), sell on day 6 (price=3), profit=3. Then buy on day 7 (price=1), sell on day 8 (price=4), profit=3. Total profit = 6.
Output: 4
Explanation: Buy on day 1 (price=1), sell on day 5 (price=5), profit=4. Total profit = 4.
We use four state variables to track the best outcomes at each stage of at most two transactions:
- Initialize buy1 and buy2 to negative infinity (haven't bought yet), sell1 and sell2 to 0.
- For each price: update buy1 = max(buy1, -price); sell1 = max(sell1, buy1 + price); buy2 = max(buy2, sell1 - price); sell2 = max(sell2, buy2 + price).
- The answer is
sell2 , the maximum profit from at most two transactions.
Complexity Analysis:
Time complexity: O(n) — single pass through the prices array.
Space complexity: O(1) — only four state variables used.