oneby7

1-D Dynamic Programming Buying and selling with states

534. Best Time to Buy and Sell Stock with Transaction Fee

Medium

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

Output: 9

Explanation: 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

Output: 0

Explanation: 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

Output: 2999999997

Explanation: 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.

prices = [2, 7, 6, 10], fee = 2

Constraints

  • 1 ≤ prices.length ≤ 105
  • 1 ≤ prices[i] ≤ 109
  • 0 ≤ fee ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.