Problem Description
Given an array of stock prices where prices[i] is the price on the iᵗʰ day, determine the maximum profit obtainable with at most two transactions. Note that you cannot hold multiple stocks at once; you must sell the stock before buying again.
Key Insights
- The problem requires the optimal selection of at most two buy-sell transactions.
- One effective strategy is to split the problem into two parts:
- For each day i, calculate the maximum profit obtainable from day 0 to i with one transaction.
- For each day i, calculate the maximum profit obtainable from day i to the end with one transaction.
- Finally, for each day, the sum of these two profits (left and right) gives a candidate answer.
- Alternatively, a state-based dynamic programming approach can track 4 states corresponding to the two transactions.
Space and Time Complexity
Time Complexity: O(n) where n is the number of days
Space Complexity: O(n) due to extra arrays used for forward and backward computations (this can be optimized to O(1) with a state variable approach)
Solution
We use a two-pass dynamic programming approach. In the first pass (forward), we compute an array "leftProfits" where leftProfits[i] is the maximum profit from day 0 to day i with one transaction. We do this by keeping track of the minimum price observed so far and calculating the profit if sold on day i. In the second pass (backward), we compute an array "rightProfits" where rightProfits[i] is the maximum profit obtainable from day i to the last day with one transaction by tracking the maximum price seen in reverse order. Finally, for every index i, the sum leftProfits[i] + rightProfits[i] represents the maximum profit achievable by completing the first transaction on or before day i and the second transaction starting from day i. The answer is the maximum sum over all i.