Sponsored
Sponsored
This approach utilizes dynamic programming with four state variables to track the profit in various stages of transactions: before the first buy, after the first buy (before the sell), after the first sell (before the second buy), and after the second buy (before the final sell). By iterating over the prices array, we update these states with the maximum profit achievable at each step.
Time Complexity: O(n), where n is the number of days (prices length).
Space Complexity: O(1), constant space used regardless of input size.
1def maxProfit(prices):
2 first_buy, first_sell = float('-inf'), 0
3 second_buy, second_sell = float('-inf'), 0
4
5 for price in prices:
6 first_buy = max(first_buy, -price)
7 first_sell = max(first_sell, first_buy + price)
8 second_buy = max(second_buy, first_sell - price)
9 second_sell = max(second_sell, second_buy + price)
10 return second_sell
11
12prices = [3, 3, 5, 0, 0, 3, 1, 4]
13print(f'Max Profit: {maxProfit(prices)}')
In Python, we use four main variables to track the transaction stages, adjusting for maximum profit. This approach efficiently computes the desired output with a simple loop.
This approach involves creating two arrays that store the maximum profit achievable from the left side to each index and from each index to the right in the prices array. Combining these two arrays helps derive the total maximum profit achievable through two transactions.
Time Complexity: O(n), as we iterate twice through prices.
Space Complexity: O(n), due to the use of two auxiliary arrays.
#include <iostream>
#include <algorithm>
int maxProfit(std::vector<int>& prices) {
if (prices.empty()) return 0;
int n = prices.size();
std::vector<int> leftProfit(n), rightProfit(n);
int minPrice = prices[0];
for (int i = 1; i < n; i++) {
leftProfit[i] = std::max(leftProfit[i - 1], prices[i] - minPrice);
minPrice = std::min(minPrice, prices[i]);
}
int maxPrice = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightProfit[i] = std::max(rightProfit[i + 1], maxPrice - prices[i]);
maxPrice = std::max(maxPrice, prices[i]);
}
int maxProfit = 0;
for (int i = 0; i < n; i++) {
maxProfit = std::max(maxProfit, leftProfit[i] + rightProfit[i]);
}
return maxProfit;
}
int main() {
std::vector<int> prices = {3, 3, 5, 0, 0, 3, 1, 4};
std::cout << "Max Profit: " << maxProfit(prices) << std::endl;
return 0;
}
In C++, this implementation employs the left and right profit arrays to maintain and combine profitability from both extremities, resulting in the maximal overall profit across all intersections of both transactions.