-
Notifications
You must be signed in to change notification settings - Fork 17
/
best-time-to-buy-and-sell-stock-with-transaction-fee.py
90 lines (66 loc) · 2.69 KB
/
best-time-to-buy-and-sell-stock-with-transaction-fee.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from functools import lru_cache
from typing import List
class Solution:
def maxProfitBruteForce(self, prices: List[int], fee: int) -> int:
def dp(pos: int, bought: bool) -> int:
if pos == len(prices):
return 0 # base case
max_profit = 0
if not bought:
# Buy stock
max_profit = max(max_profit, dp(pos + 1, True) - prices[pos] - fee)
else:
# Sell stock
max_profit = max(max_profit, dp(pos + 1, False) + prices[pos])
# Do nothing
max_profit = max(max_profit, dp(pos + 1, bought))
return max_profit
return dp(0, False)
def maxProfitTopDown(self, prices: List[int], fee: int) -> int:
@lru_cache(None)
def dp(pos: int, bought: bool) -> int:
if pos == len(prices):
return 0 # base case
max_profit = 0
if not bought:
# Buy stock
max_profit = max(max_profit, dp(pos + 1, True) - prices[pos] - fee)
else:
# Sell stock
max_profit = max(max_profit, dp(pos + 1, False) + prices[pos])
# Do nothing
max_profit = max(max_profit, dp(pos + 1, bought))
return max_profit
return dp(0, False)
def maxProfitBottomUp(self, prices: List[int], fee: int) -> int:
dp = [[0, 0] for _ in range(len(prices) + 1)]
for pos in reversed(range(len(prices))):
for bought in [True, False]:
max_profit = 0
if not bought:
# Buy stock
max_profit = max(max_profit, dp[pos + 1][True] - prices[pos] - fee)
else:
# Sell stock
max_profit = max(max_profit, dp[pos + 1][False] + prices[pos])
# Do nothing
max_profit = max(max_profit, dp[pos + 1][bought])
dp[pos][bought] = max_profit
return dp[0][False]
def maxProfit(self, prices: List[int], fee: int) -> int:
dp = [0, 0]
for pos in reversed(range(len(prices))):
dp_old = dp
dp = [0, 0]
for bought in [True, False]:
max_profit = 0
if not bought:
# Buy stock
max_profit = max(max_profit, dp_old[True] - prices[pos] - fee)
else:
# Sell stock
max_profit = max(max_profit, dp_old[False] + prices[pos])
# Do nothing
max_profit = max(max_profit, dp_old[bought])
dp[bought] = max_profit
return dp[False]