Best Time to Buy and Sell Stock with Transaction Fee

You are given the price of a stock on each day in prices, and a fee charged once for every completed trade (a buy followed by a sell). You may trade as often as you like, but you can hold at most one share at a time, so you must sell before buying again. Return the maximum profit you can make.

30:00

Best Time to Buy and Sell Stock with Transaction Fee
medium
Free written solution
Topics
Companies

You are given the price of a stock on each day in prices, and a fee charged once for every completed trade (a buy followed by a sell). You may trade as often as you like, but you can hold at most one share at a time, so you must sell before buying again. Return the maximum profit you can make.

Example 1:
Input: {"prices":[1,3,2,8,4,9],"fee":2}
Output: 8
Constraints:
  • 1≤prices.length≤5×1041 \leq \text{prices.length} \leq 5 \times 10^4

  • 1≤prices[i]<5×1041 \leq \text{prices}[i] < 5 \times 10^4

  • 0≤fee<5×1040 \leq \text{fee} < 5 \times 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"prices":[1,3,2,8,4,9],"fee":2}

Each day we keep two numbers: cash, the best profit while owning no share, and hold, the best profit while owning one. The fee is 2 per trade.

132849

CASH

no share in hand

-

<- sell: hold + price - 2
buy: cash - price ->

HOLD

one share in hand

-

bold cash: that day's best came from a salebold hold: that day's best came from a buyfee is paid once per sale
Variables
VariableValue
fee2
DepthFunction Call
Stack empty
0/14