Skip to content

Best Time to Buy and Sell Stock IV

HardDynamic Programming
Decode it first. Clues, constraints, pattern and plan before any code.

prices[i] is a stock's price on day i, and you may complete at most k trades. A trade is one buy followed later by one sell, and you can hold at most one share at a time. Return the largest total profit you can make.

prices = [5, 1, 4, 2, 9], k = 1               →  8    (buy 1, sell 9)
prices = [2, 9, 1, 3, 1, 8], k = 2            →  14   (buy 2, sell 9; buy 1, sell 8)
prices = [1, 5, 2, 8, 3, 9, 4, 10], k = 3     →  19

Constraints

  • 1 <= k <= 100
  • 1 <= prices.length <= 1000
  • 0 <= prices[i] <= 1000