Tensorum
LeetCode 123 · State Machine / Stocks

Best Time to Buy and Sell Stock III

LeetCode 123 · Hard · solution, intuition & step-by-step walkthrough

Effective second buy = price − best first profit.

HardArrayDynamic Programming
91 msruntime · beats 84%
31 MBmemory · beats 53%
1approach
8accepted runs · last 20 May 2026

This is how I solved Best Time to Buy and Sell Stock III (LeetCode 123), a hard problem from the State Machine / Stocks pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Run the one-transaction trick twice, chained. The first trade tracks its cheapest buy and best profit as usual. For the second trade, the profit already banked from the first makes the second buy effectively cheaper: its cost is price − profit₁.

Approach

  1. 1

    min_buy_t1 / max_profit_1: the classic single-trade scan.

  2. 2

    min_buy_t2 = min(min_buy_t2, price − max_profit_1): reinvest the first profit.

  3. 3

    max_profit_2 = max(max_profit_2, price − min_buy_t2): best total after two trades.

  4. 4

    Update all four in one pass; max_profit_2 is the answer (it also covers using only one trade).

How I solved it

Four-variable state machinePythonO(n) time · O(1) space
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_buy_t1 = float("inf")
        min_buy_t2 = float("inf")
        max_profit_1=0
        max_profit_2=0
        for price in prices:
            min_buy_t1=min(min_buy_t1,price)
            max_profit_1 = max(max_profit_1,price - min_buy_t1)
            min_buy_t2=min(min_buy_t2,price-max_profit_1)
            max_profit_2 =max(max_profit_2,price - min_buy_t2) 
        return max_profit_2
Loading the step-through…

Best Time to Buy and Sell Stock III — FAQ

What is the intuition behind Best Time to Buy and Sell Stock III?

Run the one-transaction trick twice, chained. The first trade tracks its cheapest buy and best profit as usual. For the second trade, the profit already banked from the first makes the second buy effectively cheaper: its cost is price − profit₁.

How do you solve Best Time to Buy and Sell Stock III (LeetCode 123)?

1. min_buy_t1 / max_profit_1: the classic single-trade scan. 2. min_buy_t2 = min(min_buy_t2, price − max_profit_1): reinvest the first profit. 3. max_profit_2 = max(max_profit_2, price − min_buy_t2): best total after two trades. 4. Update all four in one pass; max_profit_2 is the answer (it also covers using only one trade).

What is the time and space complexity of Best Time to Buy and Sell Stock III?

Time: O(n). Space: O(1). (Accepted approach: Four-variable state machine.)

What are common mistakes in Best Time to Buy and Sell Stock III?

Splitting the array at every point and running two separate scans works but is easier to get wrong. Order of updates within a day is fine here because same-day buy/sell gives zero extra profit.