To solve this problem, we'll need to find the maximum profit that can be achieved with at most two transactions. Since the price array can be quite large (1 <= prices.length <= 10^5), we need an efficient algorithm with linear time complexity, O(N).
Here's how we'll approach the problem:
-
Understand the Constraints and Limitations:
- We can perform at most two transactions.
- We cannot engage in multiple transactions simultaneously (i.e., we must sell the stock before buying again).
- We need an efficient algorithm that runs in linear time due to the large input size.
-
High-Level Idea:
- We'll use dynamic programming to keep track of the maximum profit at each day for both the first and second transactions.
- We'll perform two passes through the price array:
- Forward Pass: Calculate the maximum profit achievable from day 0 up to day
i with at most one transaction.
- Backward Pass: Calculate the maximum profit achievable from day
i to the end with at most one transaction.
- Combine the results from both passes to find the maximum total profit.
-
Detailed Steps:
Step 1: Forward Pass (First Transaction)
- Objective: For each day
i, find the maximum profit achievable from day 0 to day i with at most one transaction.
- Method:
- Initialize a variable
min_price to the first price in the array.
- Initialize an array
first_profit of the same length as prices, filled with zeros.
- Iterate through the prices from left to right:
- At each day
i:
- Update
min_price to be the minimum of min_price and prices[i].
- Calculate the maximum profit so far:
profit = prices[i] - min_price.
- Update
first_profit[i] to be the maximum of first_profit[i-1] and profit.
Example:
For prices = [3, 3, 5, 0, 0, 3, 1, 4], the first_profit array after the forward pass would look like this:
| Day (i) | Price (prices[i]) | Min Price | Profit (prices[i] - min_price) | First Profit (first_profit[i]) |
|---|
| 0 | 3 | 3 | 0 | 0 |
| 1 | 3 | 3 | 0 | 0 |
| 2 | 5 | 3 | 2 | 2 |
| 3 | 0 | 0 | 0 | 2 |
| 4 | 0 | 0 | 0 | 2 |
| 5 | 3 | 0 | 3 | 3 |
| 6 | 1 | 0 | 1 | 3 |
| 7 | 4 | 0 | 4 | 4 |
Step 2: Backward Pass (Second Transaction)
- Objective: For each day
i, find the maximum profit achievable from day i to the end with at most one transaction.
- Method:
- Initialize a variable
max_price to the last price in the array.
- Initialize an array
second_profit of the same length as prices, filled with zeros.
- Iterate through the prices from right to left:
- At each day
i:
- Update
max_price to be the maximum of max_price and prices[i].
- Calculate the maximum profit:
profit = max_price - prices[i].
- Update
second_profit[i] to be the maximum of second_profit[i+1] (if i is not the last index) and profit.
Example:
For the same prices array, the second_profit array after the backward pass would look like this:
| Day (i) | Price (prices[i]) | Max Price | Profit (max_price - prices[i]) | Second Profit (second_profit[i]) |
|---|
| 7 | 4 | 4 | 0 | 0 |
| 6 | 1 | 4 | 3 | 3 |
| 5 | 3 | 4 | 1 | 3 |
| 4 | 0 | 4 | 4 | 4 |
| 3 | 0 | 4 | 4 | 4 |
| 2 | 5 | 5 | 0 | 4 |
| 1 | 3 | 5 | 2 | 4 |
| 0 | 3 | 5 | 2 | 4 |
Step 3: Combine the Profits
- For each day
i, the total profit with two transactions can be calculated as the sum of:
first_profit[i]: Maximum profit from day 0 to day i (first transaction).
second_profit[i]: Maximum profit from day i to the end (second transaction).
- Iterate through each day and keep track of the maximum total profit.
Example:
| Day (i) | First Profit (first_profit[i]) | Second Profit (second_profit[i]) | Total Profit |
|---|
| 0 | 0 | 4 | 4 |
| 1 | 0 | 4 | 4 |
| 2 | 2 | 4 | 6 |
| 3 | 2 | 4 | 6 |
| 4 | 2 | 4 | 6 |
| 5 | 3 | 3 | 6 |
| 6 | 3 | 3 | 6 |
| 7 | 4 | 0 | 4 |
- The maximum total profit is 6.
Step 4: Edge Cases
- No Transactions: If the prices only decrease or stay the same, the maximum profit is 0.
- Single Transaction is Best: In some cases, performing only one transaction yields the maximum profit.
Final Solution in Code
def maxProfit(prices):
if not prices:
return 0
n = len(prices)
# Initialize profit arrays
first_profit = [0] * n
second_profit = [0] * n
# Forward pass
min_price = prices[0]
for i in range(1, n):
min_price = min(min_price, prices[i])
first_profit[i] = max(first_profit[i - 1], prices[i] - min_price)
# Backward pass
max_price = prices[-1]
for i in range(n - 2, -1, -1):
max_price = max(max_price, prices[i])
second_profit[i] = max(second_profit[i + 1], max_price - prices[i])
# Combine profits
max_total_profit = 0
for i in range(n):
total_profit = first_profit[i] + second_profit[i]
max_total_profit = max(max_total_profit, total_profit)
return max_total_profit
Explanation of the Code
- We initialize two arrays,
first_profit and second_profit, to keep track of the maximum profit at each day for the first and second transactions.
- In the forward pass, we iterate through the prices from left to right, updating the minimum price seen so far and calculating the maximum profit for the first transaction up to each day.
- In the backward pass, we iterate from right to left, updating the maximum price seen so far and calculating the maximum profit for the second transaction from each day to the end.
- Finally, we iterate through each day, summing the maximum profits from both transactions and keeping track of the overall maximum profit.
Time and Space Complexity
- Time Complexity: O(N), where N is the number of days. We traverse the
prices array three times.
- Space Complexity: O(N), due to the use of two additional arrays of size N. If we need to optimize space, we can use variables instead of arrays since we only need the maximum profits at each step.
Optimizing Space Complexity
We can optimize the space complexity to O(1) by using variables instead of arrays:
def maxProfit(prices):
if not prices:
return 0
# Variables for the four states
# hold1: Max profit after buying the first stock
# release1: Max profit after selling the first stock
# hold2: Max profit after buying the second stock
# release2: Max profit after selling the second stock
hold1 = hold2 = float('-inf')
release1 = release2 = 0
for price in prices:
# Update the profits in reverse order of transactions
release2 = max(release2, hold2 + price)
hold2 = max(hold2, release1 - price)
release1 = max(release1, hold1 + price)
hold1 = max(hold1, -price)
return release2
Explanation:
hold1: Maximum profit after buying the first stock (negative because we spend money).
release1: Maximum profit after selling the first stock.
hold2: Maximum profit after buying the second stock.
release2: Maximum profit after selling the second stock.
- We update
release2 and hold2 based on the previous transaction profits.
- The final answer is
release2, the maximum profit after performing at most two transactions.
Proof of Correctness
- The variables
hold1, release1, hold2, and release2 represent the optimal profits at each state.
- By iterating through the prices and updating these variables, we simulate all possible transactions.
- Since we always take the maximum of the current value and the new calculated value, we ensure that we are capturing the optimal profit at each step.
- This method efficiently computes the maximum profit without the need for additional arrays.
Conclusion
By carefully analyzing the problem and using dynamic programming techniques, we efficiently compute the maximum profit achievable with at most two transactions. The key is to track the maximum profit at each day for both the first and second transactions and combine them to find the overall maximum profit.