#188

Best Time to Buy and Sell Stock IV

Hard State machine DP (k transactions)

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

?The problem

Make at most k buy-sell transactions. 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 k trades.

Why this works: arrays buy[1..k] and sell[1..k], each built from the previous transaction's sell.

Example: k = 2, [3, 2, 6, 5, 0, 3]

buy 2 sell 6 (+4), buy 0 sell 3 (+3) → 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Huge k making the arrays and loops too big — handle k >= n/2 with the unlimited solution.

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