Given an array prices[], where prices[i] represents the price of a stock on the i-th day, find the maximum profit that can be earned by performing at most two transactions.
Each transaction consists of one buy and one sell operation, and a new transaction can begin only after the previous one is completed (i.e., you cannot hold more than one stock at a time).
Examples:
Input: prices[] = [10, 22, 5, 75, 65, 80]
Output: 87
Explanation:
Buy at 10, sell at 22, profit = 22 - 10 = 12
Buy at 5 and sell at 80, total profit = 12 + (80 - 5) = 87Input: prices[] = [100, 30, 15, 10, 8, 25, 80]
Output: 72
Explanation: Only one transaction needed here. Buy at price 8 and sell at 80.Input: prices[] = [90, 80, 70, 60, 50]
Output: 0
Explanation: Not possible to earn.
Table of Content
- [Naive Approach] Using Brute Force - O(n^2) Time and O(1) Space
- [Better Approach 1] Using Postfix Profit Array - O(n) Time and O(n) Space
- [Better Approach 2] Using Top Down Dp - O(n) Time and O(n) Space
- [Expected Approach 1] Bottom Up Dp with Space Optimization - O(n) Time and O(1) Space
- [Expected Approach 2] Further Space Optimization - O(n) Time and O(1) Space
[Naive Approach] Using Brute Force - O(n2) Time and O(1) Space
We can use the concept of maximum profit from one transaction to solve this for two transactions. For each day i, we assume the first transaction ends on or before i, and the second transaction starts after i.
- The profit from the first transaction can be computed by tracking the minimum price so far and finding the maximum difference.
- The profit from the second transaction can then be calculated by applying the same logic on the remaining days (from i + 1 onward).
By combining these two profits for every possible split point i, we get the maximum achievable profit from at most two transactions.
//Driver Code Starts
#include <iostream>
#include <vector>
using namespace std;
//Driver Code Ends
// Function to find maximum profit
// with one transaction starting from index idx
int maxProfOne(vector<int> &prices, int idx) {
int minSoFar = prices[idx], res = 0;
for (int i = idx + 1; i < prices.size(); i++) {
minSoFar = min(minSoFar, prices[i]);
res = max(res, prices[i] - minSoFar);
}
return res;
}
// Function to find maximum profit
// with at most two transactions
int maxProfit(vector<int>& prices) {
int n = prices.size();
int minSoFar = prices[0], res = 0;
for (int i = 1; i < n; i++) {
if (prices[i] > minSoFar) {
// Profit from first transaction + best profit
// from remaining days
int curr = prices[i] -