AlgoFrames

At most k transactions

Standard · Write code · about 20 min

prices[i] is the price of a stock on day i. Make at most k trades (a buy followed by a later sale), holding at most one share at a time.

Return the largest total profit.

Example 1

Input:

[2,[3,2,6,5,0,3]]

Output:

7

Buy 2, sell 6; buy 0, sell 3: 4 + 3 = 7.

Example 2

Input:

[2,[2,4,1]]

Output:

2

One trade is enough.

Constraints

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

Learn the idea first: State machine DP: stock problems, a visual lesson.

More State machine DP: stock problems problems