Problem 300
Stock Trading with K Transactions
Hard · 30 pts · Array, Dynamic Programming
Problem
You are given the price of a stock on each of N days. You may make at most K transactions, where a transaction means buying one share and selling it on a later day. You can hold at most one share at a time, so you must sell before buying again. Find the maximum total profit. Use dynamic programming over transactions: for each t from 1 to K, track the best balance after the t-th buy (buy[t] = max(buy[t], sell[t - 1] - price)) and after the t-th sell (sell[t] = max(sell[t], buy[t] + price)), updating them day by day. The answer is sell[K].
Input
First line: N and K. Second line: N prices.
Output
Print the maximum profit.
Constraints
1 <= N <= 1000; 1 <= K <= 100; 0 <= price <= 1000
Example input
6 2 3 2 6 5 0 3
Example output
7
Explanation
With prices 3 2 6 5 0 3 and K = 2, buy at 2 and sell at 6 for +4, then buy at 0 and sell at 3 for +3. The total profit is 7.