#123

Best Time to Buy and Sell Stock III

Hard State machine DP (2 transactions)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Make at most two buy-sell transactions (not overlapping). Return the maximum profit.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: at most two trades.

Why this works: four states in a chain: after buy 1, after sell 1, after buy 2, after sell 2.

Example: [3, 3, 5, 0, 0, 3, 1, 4]

buy 0 sell 3 (+3), buy 1 sell 4 (+3) → 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Splitting the array at every point and running the one-transaction solution on both sides each time — O(n²).

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon