Best Time to Buy and Sell Stock with Transaction Fee LeetCode solution in Python

1
class Solution:
2
def maxProfit(self, prices: List[int], fee: int) -> int:
3
n = len(prices)
4
lookup = {}
5

6
def f(ind, buy, lookup):
7

8
if ind == n:
9
return 0
10

11
if (ind, buy) in lookup:
12
return lookup[(ind, buy)]
13
profit = 0
14
if buy:
15
profit = max(
16
-prices[ind] + f(ind + 1, 0, lookup), f(ind + 1, 1, lookup)
17
)
18
else:
19
profit = max(
20
prices[ind] + f(ind + 1, 1, lookup) - fee, f(ind + 1, 0, lookup)
21
)
22

23
lookup[(ind, buy)] = profit
24
return lookup[(ind, buy)]
25

26
return f(0, 1, lookup)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0