-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathbest_buy_sell.py
44 lines (34 loc) · 1.18 KB
/
best_buy_sell.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
from typing import List
import math
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
# solve special cases
if not prices or k==0:
return 0
if 2*k > n:
res = 0
for i, j in zip(prices[1:], prices[:-1]):
res += max(0, i - j)
return res
# dp[i][used_k][ishold] = balance
# ishold: 0 nothold, 1 hold
dp = [[[-math.inf]*2 for _ in range(k+1)] for _ in range(n)]
# set starting value
dp[0][0][0] = 0
dp[0][1][1] = -prices[0]
# fill the array
for i in range(1, n):
for j in range(k+1):
# transition equation
dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]+prices[i])
# you can't hold stock without any transaction
if j > 0:
dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0]-prices[i])
res = max(dp[n-1][j][0] for j in range(k+1))
return res
# Tests:
if __name__ == '__main__':
Sol = Solution()
Solve = Sol.maxProfit(k = 2, prices = [2,4,1]) # k = 2, prices = [2,4,1] -> 2
print(Solve)