1-D Dynamic Programming Buying and selling with states
534. Best Time to Buy and Sell Stock with Transaction Fee
You are given an array prices, where prices[i] is the price of one share on day i, and an integer
fee. 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 again.
Every trade costs fee. A trade is one buy and the sale that follows it, and the fee is paid once for the
pair, not once for the buy and again for the sale.
Return the largest total profit you can make. The profit of one trade is the selling price minus the
buying price minus fee. If no trade makes money, return 0.
Example 1
Input: prices = [3, 9, 7, 12, 4, 10], fee = 3
9Explanation: Buy at 3 and sell at 12 for 12 − 3 − 3 = 6, then buy at 4 and sell at 10 for 3 more. Selling at 9 and buying again at 7 would save 2 on the dip but pay the fee one more time.
Example 2
Input: prices = [5, 8, 6, 9], fee = 4
0Explanation: The best trade, from 5 to 9, earns 4, and the fee takes all of it. Not trading gives 0.
Example 3
Input: prices = [1, 1000000000, 1, 1000000000, 1, 1000000000]
fee = 0
2999999997Explanation: With no fee, all three rises are worth trading, and each earns 999999999.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ prices.length ≤ 1051 ≤ prices[i] ≤ 1090 ≤ fee ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.