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 IIIarrow-up-right GitHub: Solution / Performancearrow-up-right

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).

circle-info

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

triangle-exclamation
  • 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.

Last updated