309. Best Time to Buy and Sell Stock with Cooldown

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

这道题跟 122 和 714 是一个类型,只是多了一个cooldown,可以用同一个模板来做。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) == 0:
            return 0
        cooldown = 0
        buy = -prices[0]
        sell = 0
        for price in prices[1:]:
            prevBuy = buy
            buy = max(buy,cooldown - price)
            cooldown = max(cooldown,sell)
            sell = max(sell, prevBuy + price)
        return sell

Last updated

Was this helpful?