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.
1#include <stdio.h>
2
3int maxProfit(int* prices, int pricesSize) {
4 if (pricesSize <= 1) return 0;
5 int firstBuy = -1000000, firstSell = 0, secondBuy = -1000000, secondSell = 0;
6
7 for (int i = 0; i < pricesSize; i++) {
8 firstBuy = firstBuy > -prices[i] ? firstBuy : -prices[i];
9 firstSell = firstSell > firstBuy + prices[i] ? firstSell : firstBuy + prices[i];
10 secondBuy = secondBuy > firstSell - prices[i] ? secondBuy : firstSell - prices[i];
11 secondSell = secondSell > secondBuy + prices[i] ? secondSell : secondBuy + prices[i];
12 }
13 return secondSell;
14}
15
16int main() {
17 int prices[] = {3, 3, 5, 0, 0, 3, 1, 4};
18 int size = sizeof(prices) / sizeof(prices[0]);
19 printf("Max Profit: %d\n", maxProfit(prices, size));
20 return 0;
21}
This solution initializes four state variables representing the different transaction stages. We iterate over the price list to update these states, maximizing profit at each step. The final state, secondSell
, holds the maximum profit obtainable.
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.
1
Python implementation utilizes dual lists for combining profitability potential by progressing and reversing through the data. This sums to establish the best reachable figures.