Given an array prices[], where prices[i] represents the price of a stock on the i-th day, and an integer k representing the maximum number of transactions allowed, find the maximum profit that can be earned by performing at most k transactions.
Each transaction consists of one buy and one sell operation, and a new transaction can begin only after the previous one is completed.
Examples:
Input: prices[] = [10, 22, 5, 80], k = 2
Output: 87
Explanation: Buy on 1st day at 10 and sell on 2nd day at 22. Then, again buy on 3rd day at 5 and sell on 4th day at 80. Total profit = 12 + 75 = 87Input: prices[] = [90, 80, 70, 60, 50], k = 1
Output: 0
Explanation: Not possible to earn.
Table of Content
[Naive Approach] Using Recursion - O(2n) time and O(n) space
The idea is to recursively explore all possible buy and sell decisions to find the maximum profit. To do this, we use a variable buy, which is set to 1 if we can buy a stock and 0 if we must sell the currently held one.
We start from the 0th index, and for each day i, there are two choices depending on the current state:
- If we can buy (buy == 1): We can either buy the stock today or skip the day.
profit(i, k, 1) = max(-prices[i] + profit(i + 1, k, 0), profit(i + 1, k, 1))- If we can sell (buy == 0): We can either sell the stock today or skip the day.
profit(i, k, 0) = max(prices[i] + profit(i + 1, k - 1, 1), profit(i + 1, k, 0))
The recursion terminates when all days are processed (i >= n) or no transactions remain (k <= 0), returning 0 in such cases.
//Driver Code Starts
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//Driver Code Ends
// Utility function for recursive profit calculation
int maxProfitUtil(int i, int k, int buy, vector<int> &prices) {
// Base case
if (k <= 0 || i >= prices.size()) return 0;
int res = 0;
// If we can buy, choose to buy or skip
if (buy)
res = max(maxProfitUtil(i + 1, k, 0, prices) - prices[i],
maxProfitUtil(i + 1, k, 1, prices));
// If we can sell, choose to sell or skip
else
res = max(prices[i] + maxProfitUtil(i + 1, k - 1, 1, prices),
maxProfitUtil(i + 1, k, 0, prices));
return res;
}
// Function to return maximum profit with k transactions
int maxProfit(vector<int> &prices, int k) {
return maxProfitUtil(0, k, 1, prices);
}
//Driver Code Starts
int main() {
int k = 2;
vector<int> prices = {10, 22, 5, 80};
cout << maxProfit(prices, k);
return 0;
}
//Driver Code Ends
//Driver Code Starts
import java.util.ArrayList;
class GFG {
//Driver Code Ends
// Utility function for recursive profit calculation
static int maxProfitUtil(int