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      
    
  • 相关阅读:
    端口查看netstat -tunpl |grep 25
    解释一下查找出文件并删除find /var/log -type f -mtime +7 -ok rm {} ;
    2021.6.2
    2021.6.1
    2021.5.31
    2021.5.30(每周总结)
    2021.5.28
    2021.5.27
    2021.5.26
    2021.5.25
  • 原文地址:https://www.cnblogs.com/liaohuiqiang/p/9744676.html
Copyright © 2011-2022 走看看