leetcode121.买卖股票的最佳时机I

题目要求只能买卖一次

#写法1
import sys
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price=sys.maxsize
        max_profit=0
        
        for i in range(len(prices)):
            if prices[i]<min_price:
                min_price=prices[i]
            if prices[i]-min_price>max_profit:
                max_profit=prices[i]-min_price
        return max_profit

#写法2
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        min_pri=prices[0]
        max_pro=0
        
        for i in range(1,len(prices)):
            max_pro=max(max_pro,prices[i]-min_pri)
            min_pri=min(min_pri,prices[i])
        return max_pro

猜你喜欢

转载自www.cnblogs.com/liguitar/p/11520576.html