123. Best Time to Buy and Sell Stock III

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

跟 best time to buy and sell stock 1 一样

只不过这里需要两个minCost,maxProfit来记录,因为这里有at most两个transaction

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

Last updated

Was this helpful?