0123. Best Time to Buy and Sell Stock III

Hard | Array + DP | 1272 ms (50.09%), 28.3 MB (46.16%)

Source: LeetCode - Best Time to Buy and Sell Stock III GitHub: Solution / Performance

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete at most two transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

We can use Final State Machine to solve the series of these problems.

Note that this problem limits us to have at most two transactions, so we need to maintain an array with the size "2+1" (one for day 0 initialization) to record MAX profit among one or two transactions.

Keep in mind that a complete transaction means "Buy + Sell". In other words, buying new stock equals creating a new transaction. Thus, when we calculate the hold state's profit with i transactions, for buying stock, we need to take the no-hold state's profit with "i-1" transaction.

  • Hold state means you hold the stock.

    • Since you don't have any stocks at the beginning, the profit at this state is initialized with negative infinity.

    • The profit in this state is calculated by: previous no-hold state's profit - current stock price (= buy) = no-hold state's profit w/ 'i-1' transactions - cur. stock price

  • No-Hold state means you do not hold any stocks.

    • Since you don't have any stocks at the beginning (you're initially at this state ), the profit at this state is initialized with 0.

    • The profit in this state is calculated by: previous hold state's profit + current stock price (= sell) = hold state's profit w/ 'i' transactions + cur. stock price

    • Return the profit at the no-hold state as the maximum profit since the hold state still has stock on hold.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        #  (base case)
        if len(prices) == 0 or len(prices) == 1: return 0
        
        # ==================================================
        #  Array + Dynamic Programming              (FSM)  =
        # ==================================================
        # time  : O(n)
        # space : O(1)
        
        # '+1' for day 0 initialization
        T = 2 + 1
        hold, noHold = [float('-inf')] * T, [0] * T
        
        for price in prices:
            for i in range(1, T):
                preHold, preNoHold = hold[i], noHold[i]
                
                hold[i]   = max(preHold,   noHold[i-1] - price)
                noHold[i] = max(preNoHold, preHold     + price)
                
        return noHold[-1]

Last updated