leetcode

Description:

leetcode-122

Submission:

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
class :
def maxProfit(self, prices: List[int]) -> int:
days = len(prices)
if (days <= 1):
return 0
else:
if (sorted(prices) == prices):
return prices[-1] - prices[0]
elif (reversed(prices) == prices):
return 0
else:

profit = 0
buy = -1 # 本来是0,但是没想到price还能是0
sell = -1
prices.insert(0, float('inf')) # 第一天只考虑买,最后一天只考虑卖
prices.append(0)
for i in range(1, days+1):
if (prices[i] <= prices[i+1] and prices[i] <= prices[i-1]):
buy = prices[i]
elif (prices[i] >= prices[i+1] and prices[i] >= prices[i-1]):
if (buy != -1): # 只有在buy的前提下,才考虑sell
sell = prices[i]

if (buy != -1 and sell != -1):
profit += (sell - buy)
buy = -1
sell = -1
return profit

Acceptance:

ac