Skip to content

Commit cfccebe

Browse files
authored
Update 05. With Transaction-Fee.py
1 parent 703f73a commit cfccebe

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
2+
# Same as "02. As Many Transactions As You Like.py" with transaction fee
23

34
class Solution:
45
def maxProfit(self, prices: List[int], fee: int) -> int:
5-
obsp = - prices[0] # Old Brought State Profite
6-
ossp = 0 # Old Sold State Profite
7-
8-
for i in range(1, len(prices)):
9-
nbsp = 0 # New Brought State Profit
10-
nssp = 0 # New Sold State Profit
11-
12-
nbsp = max(ossp - prices[i], obsp)
13-
nssp = max(obsp + prices[i] - fee, ossp)
14-
15-
obsp = nbsp
16-
ossp = nssp
17-
18-
return ossp
6+
memo = {}
7+
def solve(i,can_sell):
8+
if i == len(prices): return 0
9+
if (i,can_sell) in memo: return memo[(i,can_sell)]
10+
if can_sell == 1:
11+
profit = max(prices[i] + solve(i+1,0) - fee, solve(i+1,1))
12+
else:
13+
profit = max(-prices[i] + solve(i+1,1), solve(i+1,0))
14+
memo[(i,can_sell)] = profit
15+
return profit
16+
return solve(0,0)
1917

20-
# Time: O(n)
21-
# Space: O(1)
18+
# Time: O(2*N)
19+
# Space: O(2*N)

0 commit comments

Comments
 (0)