121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Buy stock 系列的一个中心思想,控制成本!

因为我们想要最大利润,那我们永远都是greedy的想要最小的成本。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        minCost = float("inf")
        maxProfit = 0
        for price in prices:
            maxProfit = max(maxProfit, price - minCost)
            minCost = min(minCost,price)
        return maxProfit
        

Last updated

Was this helpful?