leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机 python 最简代码 如何减少冗余操作

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # method one
#        考虑特殊情况空列表, 效率低
        # return max([max(prices[i:])-prices[i] for i in range(len(prices))])  if prices else 0


        # method two  还是效率低
        # res = 0
        # while prices:
        #     max_price = max(prices)
        #     tmp = max_price - min(prices[:prices.index(max_price)+1])  
        #     if tmp < res:
        #         return res
        #     else:
        #         res = tmp
        #     prices.remove(max_price)
        # return 0



        # method three  时间复杂度 n ,空间复杂度1 ,不用冗余的max()操作
        profit , min_price = 0 , float('inf')
        for price in prices:
            profit = max(price - min_price , profit)
            min_price = min(price , min_price) 
        return profit

猜你喜欢

转载自blog.csdn.net/huhehaotechangsha/article/details/80838315