Best profit with at most K trades
The price of a share is known for N days. A trade is buying one share on one day and selling it on a later day. You may hold at most one share at a time and make at most K trades. Find the largest total profit (0 if no trade helps).
Input
First line: N and K. Second line: N prices.
Output
The largest total profit.
Constraints
1 ≤ N ≤ 10^5; 1 ≤ K ≤ 100; 1 ≤ price ≤ 10^4.
Example 1
Input:
6 2
3 2 6 5 0 3
Output:
7Example 2
Input:
5 1
7 1 5 3 6
Output:
5Example 3
Input:
4 2
5 4 3 2
Output:
0Hint: Keep two values per trade count j: the best money while holding a share (buy[j]) and while not holding (sell[j]). For each price: buy[j] = max(buy[j], sell[j − 1] − price) and sell[j] = max(sell[j], buy[j] + price). The answer is sell[K].