1-D Dynamic Programming Buying and selling with states
536. Best Time to Buy and Sell Stock II
You are given an array prices, where prices[i] is the price of one share on day i. You may buy and
sell as many times as you like, but you can hold at most one share at a time. So you must sell the share
you hold before you buy another. You may sell a share and buy a new one on the same day.
Return the largest total profit you can make. The profit of one trade is its selling price minus its buying price. If no trade makes money, return 0.
Example 1
Input: prices = [6, 2, 5, 3, 9, 8, 11]
12Explanation: Buy at 2 and sell at 5, buy at 3 and sell at 9, then buy at 8 and sell at 11. The three trades make 3 + 6 + 3 = 12. The best single trade, from 2 to 11, makes only 9.
Example 2
Input: prices = [9, 6, 6, 3, 0]
0Explanation: The price never rises, so every trade loses money or breaks even. Not trading gives 0.
Example 3
Input: prices = [1000000000, 0, 1000000000, 0, 1000000000, 0, 1000000000]
3000000000Explanation: Each of the three rises from 0 to 1000000000 is a trade worth making.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ prices.length ≤ 1050 ≤ prices[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.