SDE & MLE Prep

123. Best Time to Buy and Sell Stock III

Problem

prices[i] is a stock's price on day i. Make at most two buy-then-sell transactions (holding at most one share at a time) and return the maximum profit.

Example: [3,3,5,0,0,3,1,4] → 6; [1,2,3,4,5] → 4

Constraints: n ≤ 10⁵.

At most two transactions → four running states: buy1, sell1, buy2, sell2. Each is the best balance after that action so far; buy2 builds on sell1.

Complexity: O(n) time, O(1) space.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy1 = buy2 = float("-inf")
        sell1 = sell2 = 0
        for p in prices:
            buy1 = max(buy1, -p)
            sell1 = max(sell1, buy1 + p)
            buy2 = max(buy2, sell1 - p)
            sell2 = max(sell2, buy2 + p)
        return sell2