1-D Dynamic Programming Buying and selling with states
537. Best Time to Buy and Sell Stock III
You are given an array prices, where prices[i] is the price of one share on day i. You may make at
most two trades. A trade is buying one share on one day and selling it on a later day.
You can hold at most one share at a time, so the first trade must be sold before the second one is bought. Selling and buying again on the same day is allowed.
Return the largest total profit you can make. The profit of a trade is the selling price minus the buying price. You may also make one trade or none, and if no trade makes money, return 0.
Example 1
Input: prices = [3, 1, 7, 2, 9, 5, 6]
13Explanation: Buy at 1 and sell at 7 for 6, then buy at 2 and sell at 9 for 7. The best single trade, from 1 to 9, makes only 8, and the rise from 5 to 6 would need a third trade.
Example 2
Input: prices = [0, 2, 5, 9, 10]
10Explanation: The price never falls, so one trade from 0 to 10 is best. Splitting it into two trades earns nothing more.
Example 3
Input: prices = [9, 7, 7, 3]
0Explanation: The price never rises, so every trade loses money or breaks even. Not trading gives 0.
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.