loading

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

hardLeetCode #188ArrayDynamic Programming

Maximum profit with at most k transactions.

Algorithm Pattern

DP with k Transactions

Key Idea

For each of k transaction slots, track best buy price and best sell profit.

Step-by-Step Approach

  1. Initialize buy[j] = -Infinity, sell[j] = 0
  2. For each price:
  3. For j from k to 1:
  4. sell[j] = max(sell[j], buy[j] + price)
  5. buy[j] = max(buy[j], sell[j-1] - price)
  6. Return sell[k]

Related Problems