首页 > 其他 > 详细

121. Best Time to Buy and Sell Stock

时间:2018-10-05 14:34:01      阅读:128      评论:0      收藏:0      [点我收藏+]

问题描述

给定一个数组,第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

原文:https://www.cnblogs.com/liaohuiqiang/p/9744676.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!