1-D Dynamic Programming Buying and selling with states
535. Best Time to Buy and Sell Stock IV
You are given an integer k and an array prices, where prices[i] is the price of one share on day i.
You may make at most k trades. You can hold at most one share at a time, so you must sell the share you
hold before you buy again.
A trade is one buy and the sale that follows it. The buy and the sale together count as one trade, not two.
Return the largest total profit you can make. The profit of one trade is the selling price minus the buying price. If no trade makes money, return 0.
Example 1
Input: k = 2, prices = [3, 2, 6, 5, 8, 1, 4]
9Explanation: Buy at 2 and sell at 8 for 6, keeping the share through the dip to 5. Then buy at 1 and sell at 4 for 3 more. Selling at 6 and buying again at 5 would need a third trade.
Example 2
Input: k = 5, prices = [8, 0, 5, 5, 2]
5Explanation: Buy at 0 and sell at 5. The price never rises again, so the other four trades stay unused.
Example 3
Input: k = 3
prices = [0, 1000000000, 0, 1000000000, 0, 1000000000, 0, 1000000000]
3000000000Explanation: The price rises by 109 four times, but only three trades are allowed.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ k ≤ 1001 ≤ prices.length ≤ 1050 ≤ prices[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.