forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0188.py
More file actions
26 lines (22 loc) · 716 Bytes
/
Copy path0188.py
File metadata and controls
26 lines (22 loc) · 716 Bytes
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
class Solution:
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
p_len = len(prices)
if k >= p_len//2:
return self.greedy(prices)
buy, sell = [-prices[0]]*k , [0]*(k+1)
for p in prices[1:]:
for i in range(k):
buy[i] = max(buy[i], sell[i-1]-p)
sell[i] = max(sell[i], buy[i]+p)
return max(sell)
def greedy(self, prices):
res = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
res += prices[i] - prices[i-1]
return res