Best Time to Buy and Sell Stock with Transaction Fee

Implement maxProfit

Given daily stock `prices`, buy and sell as many times as you like — no two positions open at once, so a share must be sold before another is bought — but every completed round trip costs a flat `fee`, charged when the position closes. Maximize total profit. Every day only asks one question: given whether a share is currently held, is acting (buying into nothing, or selling out of a position) better than leaving things exactly as they are? Two running totals capture everything needed to answer that — the best result with nothing held, and the best result already holding one share — and each day's decision only ever needs yesterday's version of those two numbers. The fee just gets folded into the moment of selling, so a trade only ever gets taken when the price gap actually covers it.

Example 1:

Input: prices = [1,3,2,8,4,9], fee = 2

Output: 8

Example 2:

Input: prices = [1,2], fee = 5

Output: 0

Example 3:

Input: prices = [7,6,4,3,1], fee = 1

Output: 0

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ prices.length ≤ 10
  • 0 ≤ prices[i] ≤ 1000
  • 0 ≤ fee ≤ 100

prices =

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

fee =

2