less than 1 minute read

123. Best Time to Buy and Sell Stock III (hard)

class Solution:
    def maxProfit(self, arr: List[int]) -> int:
        n = len(arr)
        sell = [0] * n
        for _ in range(2):
            buy = -arr[0]
            profit = 0
            for i in range(1, n):
                buy = max(buy, sell[i] - arr[i])
                profit = max(profit, arr[i] + buy)
                sell[i] = profit
        return sell[-1]