121. Best Time to Buy and Sell Stock

遍历 prices,维护一个当前可能的最低买入价格,就可以计算每天的可能最高利润,遇到更高利润的就更新。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy, profit = float('inf'), 0
        for p in prices:
            buy = min(buy, p)
            profit = max(profit, (p - buy))
        return profit

Last updated

Was this helpful?