AlgoFrames

Buy and sell with a transaction fee

Standard · Write code · about 12 min

prices[i] is the price of a stock on day i. Make as many trades as you like, holding at most one share at a time. Every sale costs fee.

Return the largest total profit.

Example 1

Input:

[[1,3,2,8,4,9],2]

Output:

8

Buy 1, sell 8 (pay 2); buy 4, sell 9 (pay 2): 5 + 3 = 8.

Example 2

Input:

[[1,3,7,5,10,3],3]

Output:

6

One trade from 1 to 10 beats two trades.

Constraints

  • 1 ≤ prices.length ≤ 5 · 10⁴
  • 0 ≤ prices[i], fee ≤ 5 · 10⁴

Learn the idea first: State machine DP: stock problems, a visual lesson.

More State machine DP: stock problems problems