[Leetcode] 121. 买卖股票的最佳时机 python3

 [Leetcode] 121. 买卖股票的最佳时机 python3_第1张图片

别人的代码

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        if len(prices) < 2:
            return 0
        minimum = prices[0]
        profit = 0
        for i in prices:
            minimum = min(i, minimum)  #保留最小买入价格
            profit = max(i-minimum,profit) #最大收益
     
        return profit

分析:不断寻找最小买入价格和最大利润

prices = [7,1,5,3,6,4]
profit = 0
minimum = prices[0]
for i in prices:
    minimum = min(i, minimum)     #最小买入价格
    profit = max(i - minimum, profit) #最大利润
    print(i,minimum,profit)

输出:

7 7 0
1 1 0
5 1 4
3 1 4
6 1 5
4 1 5

 

你可能感兴趣的:(Leetcode,python,LeetCode,list)