假设给定的数组为:
[7, 1, 5, 3, 6, 4]
如果我们在图表上绘制给定数组中的数字,我们将会得到: 使我们感兴趣的点是上图中的峰和谷。我们需要找到最小的谷之后的最大的峰。 我们可以维持两个变量——minprice 和 maxprofit,它们分别对应迄今为止所得到的最小的谷值和最大的利润(卖出价格与最低价格之间的最大差值)。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minP = float('inf') # 最小的价格
maxP = 0 # 最大的利润
for p in prices:
if p maxP:
maxP = p - minP
return maxP