121. Best Time to Buy and Sell Stock

Posted liaohuiqiang

tags:

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

问题描述

给定一个数组,第i个元素表示第i天股票的价格,只能买卖一次,求最大利润

思路

遍历一次数组,不断更新“最小的股票价格”,并计算当前股票价格和最小股票的差,如果大于最大利润,则更新最大利润。
时间复杂度O(n),空间复杂度O(1)。

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if(len(prices) == 0):
            return 0
        minPrice = prices[0]
        maxProfit = 0
        for i in range(1,len(prices)):
            if(prices[i] < minPrice):
                minPrice = prices[i]
            elif(prices[i] - minPrice > maxProfit):
                maxProfit = prices[i] - minPrice
        return maxProfit      

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