当前位置:网站首页>Leetcode121 timing of buying and selling stocks

Leetcode121 timing of buying and selling stocks

2022-06-25 15:10:00 Milanien

difficulty : Simple

Title Description

Power button

Ideas

Find the maximum difference between the future price of the stock minus the past price , That is, the maximum profit , If the future price is always lower than the past price , Then the profit is 0.

Code

1. Exhaustive method

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(len(prices)):
            for j in range(i+1,len(prices)):
                tmp = prices[j]-prices[i]
                if tmp > profit:
                    profit = tmp
        return profit

Time limit exceeded .

2. Calculate the maximum profit while finding the lowest price

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        minprice = 20000000
        for i in range(len(prices)):
            tmp = prices[i]-minprice      
            if tmp > profit:
                profit = tmp
            if prices[i] < minprice:
                minprice = prices[i]
        return profit

原网站

版权声明
本文为[Milanien]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200510239291.html