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
            

猜你喜欢

转载自blog.csdn.net/weixin_42095500/article/details/82957358