问题描述:

Leetcode初级算法 买卖股票的最佳时机 Python

算法思路:

一个很自然的想法是找到数组的最大值和最小值,相减得到最大差值。但因为是买卖股票,售出必须发生在买入之后,所以利润对应的买入买出价不一定是数组的极值。举例说明:假设数组的极值为max,min,最佳的买入卖出价格为buy,sell,如果这几个元素的相对顺序为:max,buy,sell,min,显然min和max无法影响答案,因为buy必须放在sell的前面。

稍微调整下思路,我们只需要扫描价格数组,维护一个最小值,当前元素-最小值>最大利润时,更新最大利润即可。

 

代码:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if prices == []: return 0
        profit,min = 0, prices[0]
        for price in prices:
            if price < min:
                min = price
            else:
                profit = max(profit,price-min)
        return profit
            

相关文章:

  • 2021-10-03
  • 2022-12-23
  • 2021-11-24
  • 2022-12-23
  • 2021-12-06
  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-13
  • 2021-12-07
  • 2021-11-04
  • 2021-12-26
  • 2021-10-29
  • 2021-08-26
  • 2022-12-23
相关资源
相似解决方案