zoukankan      html  css  js  c++  java
  • 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      
    
  • 相关阅读:
    第一阶段意见评论
    软件工程--第十一周学习进度
    第一阶段SCRUM冲刺 10
    冲刺(三)
    冲刺(二)
    冲刺(一)
    梦断代码阅读笔记01
    第八周总结
    NABCD项目分析
    第七周总结
  • 原文地址:https://www.cnblogs.com/liaohuiqiang/p/9744676.html
Copyright © 2011-2022 走看看