LeetCode #121. Best Time to Buy and Sell Stock

Posted 老鼠司令

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode #121. Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

题目

121. Best Time to Buy and Sell Stock


解题方法

用一个变量minprice记录当前已经遍历过的最小价格,再用一个变量maxprofit记录当前已经遍历过的最大利润,如果price[i] > minprice,就计算最大利润是否需要增加;否则计算最小价格是否需要改变。


代码

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        minprice = prices[0]
        maxprofit = 0
        for i in range(1, len(prices)):
            if prices[i] > minprice:
                maxprofit = max(maxprofit, prices[i] - minprice)
            else:
                minprice = min(minprice, prices[i])
        return maxprofit

以上是关于LeetCode #121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章