prices[i] is the price of one stock on day i, and k is how many trades you may make. A trade is one purchase followed later by one sale. You can hold at most one share at a time, so you must sell before buying again.
Return the largest total profit you can make with at most k trades. If no trade earns money, return 0.
Example 1
Input: k = 2, prices = [3, 1, 5, 2, 6] Output: 8 Why: buy at 1, sell at 5, then buy at 2, sell at 6
2 more examples and the constraints
Example 2
Input: k = 1, prices = [7, 4, 9, 1, 3] Output: 5 Why: one trade only: 4 to 9 beats 1 to 3
Example 3
Input: k = 3, prices = [9, 8, 6, 3] Output: 0 Why: the price only falls, so make no trade
Constraints
- 1 ≤ k ≤ 100
- 1 ≤ length of prices ≤ 1,000
- 0 ≤ prices[i] ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Table, try every buy dayO(k·n²)
- Running buy and sell per tradeO(n·k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for k = 100 and 1,000 days | Verdict |
|---|---|---|---|
| Table, try every buy day | O(k·n²) | Correct; the inner scan is wasted work | |
| Running buy and sell per trade | O(n·k) | Best; one update per day and trade |
n = number of days, k = most trades allowed.
Edge cases to test
- One day. There is no day to sell on, so the answer is 0.
- Prices only fall. Every trade loses money;
sell[k]stays 0. - k larger than needed. With k = 100 and 6 days, only 3 trades are possible. At most means the extra ones are simply unused.
- One long rise. [1, 2, 3, 4, 5, 6] with k = 2 gives 5: one trade from 1 to 6 is as good as any split.
- Fewer trades than rises. With k = 2 and three rises, the two most profitable ones win, possibly by merging two rises into one trade.
Common mistakes
- Starting
buy[t]at 0 instead of −∞, which pretends you got a share for free. - Updating
buy[t]fromsell[t]instead ofsell[t − 1], so one trade's profit pays for itself. - Using
Integer.MIN_VALUEfor −∞ in Java or C++ and adding a price to it, which overflows.
How to talk through it
- 1Clarify. Is it at most k trades or exactly k? Can I buy and sell on the same day? Is one share the limit?
- 2Define the table. Best profit by day i with at most t trades, and say the two choices: sell nothing today, or close trade t today.
- 3Spot the repeated scan. The scan over buy days keeps recomputing a running maximum of
best[t − 1][j] − prices[j]. - 4Keep two arrays.
buy[t]andsell[t], updated once per day and trade: O(n·k) time, O(k) space. - 5Test out loud. Run one day, falling prices, and a k much larger than the number of days.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?