VISUALGO//PROBLEMS
best time to buy and sell stock with transaction fee · dp – multidimensionalmedium
prices ↑holdcash
1
·
·
0
3
·
·
1
2
·
·
2
8
·
·
3
4
·
·
4
9
·
·
5
step
·
ELEMENTS
prices
fee
Python
def maxProfit(prices: list[int], fee: int) -> int:
hold = -prices[0] # best profit while owning a share
cash = 0 # best profit while owning nothing
for price in prices[1:]:
hold, cash = max(hold, cash - price), max(cash, hold + price - fee)
return cash