Leetcode-121-买卖股票的最佳时机

“哨兵”的经典操作方法

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):

def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not len(prices):

return 0

m = prices[0]
n = 0

for val in prices:
if val < m:
m = val
else:
profit = val - m

if profit > n:
n = profit
return n

这一题主要提供的思路是创建两个“哨兵”,m用来判断是否有比当前小的值,有的话就进行替换。n用来储存最大的利润值,最终根据列表中两个相邻差值最大的值作为结果返回。