|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate maximum profit |
| 4 | + int solve(vector<int>& prices, int index, int buy, int limit){ |
| 5 | + int n = prices.size(); |
| 6 | + |
| 7 | + // Base case: if we've processed all days (index == n) or no more transactions can be made (limit == 0) |
| 8 | + if(index == n || limit == 0) return 0; |
| 9 | + |
| 10 | + int profit = 0; |
| 11 | + |
| 12 | + // If we are allowed to buy (buy == 1) |
| 13 | + if(buy){ |
| 14 | + // Option 1: Buy the stock today and recurse for the next day with the buy flag set to 0 (indicating we can sell next) |
| 15 | + // Option 2: Skip the current day and proceed to the next day with the buy flag still set to 1 |
| 16 | + profit = max((-prices[index] + solve(prices, index+1, 0, limit)), |
| 17 | + (0 + solve(prices, index+1, 1, limit))); |
| 18 | + } else { |
| 19 | + // If we are allowed to sell (buy == 0) |
| 20 | + // Option 1: Sell the stock today, reduce the transaction limit by 1 and proceed to the next day with buy flag set to 1 |
| 21 | + // Option 2: Skip the current day and proceed to the next day with buy flag still set to 0 |
| 22 | + profit = max((+prices[index] + solve(prices, index+1, 1, limit-1)), |
| 23 | + (0 + solve(prices, index+1, 0, limit))); |
| 24 | + } |
| 25 | + |
| 26 | + return profit; |
| 27 | + } |
| 28 | + |
| 29 | + // Main function to return the maximum profit |
| 30 | + int maxProfit(vector<int>& prices) { |
| 31 | + // Starting from day 0, we can buy the stock, and we are allowed to make at most 2 transactions |
| 32 | + return solve(prices, 0, 1, 2); |
| 33 | + } |
| 34 | +}; |
0 commit comments