121. Best Time to Buy and Sell Stock

问题

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

Input: [7,1,5,3,6,4]
Output: 5
Input: [7,6,4,3,1]
Output: 0

思路

遍历一次数组,不断更新“最小的股票价格”,并计算当前股票价格和最小股票的差,如果大于最大利润,则更新最大利润。

时间复杂度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      
原文地址:https://www.cnblogs.com/liaohuiqiang/p/9744676.html