Best Time to Buy and Sell Stock IV

Hard#188states

You get a number k and the price of one share for each day. Make at most k trades, each a buy and a later sell, holding one share at a time. Find the largest total profit, or 0 if no trade pays. Our example: k = 2, prices [1, 6, 4, 9, 2, 5] → 11, from 1 → 9 and 2 → 5.

input
k: how many deals at most; prices: the price of a stock day by day, prices[i] on day i.
returns
The largest profit from at most k deals. A deal buys one share and sells it on a later day; each next deal buys no earlier than the one before it sells.
constraints
  • 1 ≤ k ≤ 100
  • 1 ≤ prices.length ≤ 1000
  • 0 ≤ prices[i] ≤ 1000
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} k
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(k, prices) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more dynamic programming (dp) problems

Pattern “Dynamic programming (DP)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.