Best Time to Buy and Sell Stock IV

Implement maxProfit

Given daily stock `prices` and a transaction limit `k`, complete at most `k` buy-sell transactions — never holding more than one share, and always selling before buying again. Maximize total profit; `k = 0` always yields 0. This is the two-transaction problem stretched to an arbitrary count: instead of four named variables for buy1/sell1/buy2/sell2, keep two arrays of length k+1, `buy[t]` and `sell[t]`, one pair of slots per transaction number. Sweeping through the prices once, and inside that updating slot 1 through slot k in order, `buy[t]` only ever reads `sell[t-1]` — the profit already locked in by finishing the transaction before it — so every slot is always built from information that's already settled for the current day before it's needed.

Example 1:

Input: k = 2, prices = [2,4,1]

Output: 2

Example 2:

Input: k = 2, prices = [3,2,6,5,0,3]

Output: 7

Example 3:

Input: k = 0, prices = [1,2,3]

Output: 0

+ 6 hidden test cases run on Submit.

Constraints:

  • 0 ≤ k ≤ 5
  • 1 ≤ prices.length ≤ 10
  • 0 ≤ prices[i] ≤ 1000
  • at most k buy-sell transactions are allowed; you must sell before buying again

k =

2

prices =

[2, 4, 1]