Best Time to Buy and Sell Stock IV
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 dayi.- returns
- The largest profit from at most
kdeals. 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
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more dynamic programming (dp) problems
- 70Climbing StairsEasysolve
- 121Best Time to Buy and Sell StockEasysolve
- 198House RobberMediumsolve
- 322Coin ChangeMediumsolve
- 300Longest Increasing SubsequenceMediumsolve
- 62Unique PathsMediumsolve
- 1143Longest Common SubsequenceMediumsolve
- 53Maximum SubarrayMediumsolve
- 918Maximum Sum Circular SubarrayMediumsolve
- 139Word BreakMediumsolve
- 120TriangleMediumsolve
- 64Minimum Path SumMediumsolve
- 63Unique Paths IIMediumsolve
- 97Interleaving StringMediumsolve
- 72Edit DistanceMediumsolve
- 221Maximal SquareMediumsolve
- 123Best Time to Buy and Sell Stock IIIHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.