Best Time to Buy and Sell Stock III

Pattern: Stock buy and sell

hard

At most two transactions. Keep four numbers: the best money after the first buy, first sale, second buy and second sale; each is updated from the one before it.

The problem

Return the most profit from at most two buy-then-sell transactions (at most one share held at a time).

Think first

  • What stages can you be in?
  • Which stage does each come from?
  • Why can the updates use today's new values?

Hints

    Brute force, and why it fails

    Try every split point and the best single transaction on each side: O(n²), or O(n) with two passes.

    The key insight

    Four running maxima capture every way to do at most two transactions in one pass.

    Dry run

    [3, 3, 5, 0, 0, 3, 1, 4]. First: buy at 0, sell at 3: 3.

    Step 1 of 2

    The plan

    buy1 = buy2 = -inf; sell1 = sell2 = 0
    for p: buy1 = max(buy1, -p); sell1 = max(sell1, buy1 + p)
           buy2 = max(buy2, sell1 - p); sell2 = max(sell2, buy2 + p)
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Four numbers.

    Edge cases

    • One transaction is best.
    • Falling prices: 0.
    • One day: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int maxProfit(int[] prices) {
            int buy1 = Integer.MIN_VALUE, sell1 = 0, buy2 = Integer.MIN_VALUE, sell2 = 0;   // money after each step
            for (int p : prices) {
                buy1 = Math.max(buy1, -p);          // the first buy
                sell1 = Math.max(sell1, buy1 + p);  // the first sale
                buy2 = Math.max(buy2, sell1 - p);   // the second buy, paid from the first profit
                sell2 = Math.max(sell2, buy2 + p);  // the second sale
            }
            return sell2;
        }
    }

    C++

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int buy1 = INT_MIN, sell1 = 0, buy2 = INT_MIN, sell2 = 0;   // money after each step
            for (int p : prices) {
                buy1 = max(buy1, -p);               // the first buy
                sell1 = max(sell1, buy1 + p);       // the first sale
                buy2 = max(buy2, sell1 - p);        // the second buy, paid from the first profit
                sell2 = max(sell2, buy2 + p);       // the second sale
            }
            return sell2;
        }
    };

    Python

    class Solution:
        def maxProfit(self, prices: list[int]) -> int:
            buy1 = buy2 = float("-inf")             # money after each step
            sell1 = sell2 = 0
            for p in prices:
                buy1 = max(buy1, -p)                # the first buy
                sell1 = max(sell1, buy1 + p)        # the first sale
                buy2 = max(buy2, sell1 - p)         # the second buy, paid from the first profit
                sell2 = max(sell2, buy2 + p)        # the second sale
            return sell2

    Common mistakes

    • Allowing overlapping transactions.
    • Starting buys at 0.

    Similar problems