loading

Best Time to Buy and Sell Stock III — Step-by-Step Visualization

hardLeetCode #123ArrayDynamic Programming

Maximum profit with at most 2 transactions.

Algorithm Pattern

State Machine DP (4 States)

Key Idea

Track buy1, sell1, buy2, sell2 states updated greedily each day.

Step-by-Step Approach

  1. buy1 = min(buy1, price)
  2. profit1 = max(profit1, price - buy1)
  3. buy2 = min(buy2, price - profit1)
  4. profit2 = max(profit2, price - buy2)
  5. Return profit2

Related Problems