#include <stdio.h>
#include <stdlib.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int maxProfitTwoTransactions(int* prices, int pricesSize) {
if (pricesSize == 0) return 0;
int* profit = (int*)calloc(pricesSize, sizeof(int));
int min_price = prices[0];
for (int i = 1; i < pricesSize; i++) {
min_price = (prices[i] < min_price) ? prices[i] : min_price; // update min price
profit[i] = max(profit[i - 1], prices[i] - min_price); // max profit if sold today
}
int max_price = prices[pricesSize - 1];
int max_total_profit = profit[pricesSize - 1];
for (int i = pricesSize - 2; i >= 0; i--) {
max_price = (prices[i] > max_price) ? prices[i] : max_price; // update max price
int total_profit = max_price - prices[i] + profit[i]; // profit if buy today and sell later plus previous profit
max_total_profit = max(max_total_profit, total_profit); // max of all
}
free(profit);
return max_total_profit;
}
int main() {
int prices[] = {7, 1, 5, 3, 6, 4};
int size = sizeof(prices) / sizeof(prices[0]);
int max_profit = maxProfitTwoTransactions(prices, size);
printf("Max profit with at most 2 transactions: %d\n", max_profit);
return 0;
}min_price = (prices[i] < min_price) ? prices[i] : min_price;
update minimum price seen so far to buy low
profit[i] = max(profit[i - 1], prices[i] - min_price);
calculate max profit if sold on day i with one transaction
max_price = (prices[i] > max_price) ? prices[i] : max_price;
update maximum price seen so far from right to buy high later
int total_profit = max_price - prices[i] + profit[i];
combine profit of second transaction starting at day i with first transaction profit
max_total_profit = max(max_total_profit, total_profit);
keep track of maximum combined profit
Max profit with at most 2 transactions: 7