Skip to the code
+50 XP

#555 At Most K Trades

hard

A portfolio tool shows daily prices in prices. You may complete at most k trades, where a trade is one buy followed later by one sell, and you may hold at most one share at a time.

Write profitWithLimit(prices, k) that returns the largest total profit.

Example 1

Input: prices = [4,3,7,6,1,4], k = 2
Output: 7

Buy at 3 and sell at 7, then buy at 1 and sell at 4: 4 + 3.

Example 2

Input: prices = [4,3,7,6,1,4], k = 1
Output: 4

With one trade, buying at 3 and selling at 7 is best.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 1000
  • 0 <= k <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).