|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate maximum profit with memoization |
| 4 | + int solve(vector<int>& prices, int index, int buy, int limit, vector<vector<vector<int>>>& dp){ |
| 5 | + int n = prices.size(); |
| 6 | + |
| 7 | + // Base case: If we have reached the end of the prices array (index == n) or no transactions left (limit == 0) |
| 8 | + if(index == n || limit == 0) return 0; |
| 9 | + |
| 10 | + // Check if the result for the current state has already been computed (memoized) |
| 11 | + if(dp[index][buy][limit] != -1) return dp[index][buy][limit]; |
| 12 | + |
| 13 | + int profit = 0; |
| 14 | + |
| 15 | + // If we are allowed to buy (buy == 1) |
| 16 | + if(buy){ |
| 17 | + // Option 1: Buy the stock today, and move to the next day (after buying, we can't buy again) |
| 18 | + // Option 2: Skip buying and move to the next day, still with the option to buy |
| 19 | + profit = max((-prices[index] + solve(prices, index+1, 0, limit, dp)), |
| 20 | + (0 + solve(prices, index+1, 1, limit, dp))); |
| 21 | + } else { |
| 22 | + // If we are allowed to sell (buy == 0) |
| 23 | + // Option 1: Sell the stock today, reduce the transaction limit by 1 and move to the next day (after selling, we can buy again) |
| 24 | + // Option 2: Skip selling and move to the next day, still with the option to sell |
| 25 | + profit = max((+prices[index] + solve(prices, index+1, 1, limit-1, dp)), |
| 26 | + (0 + solve(prices, index+1, 0, limit, dp))); |
| 27 | + } |
| 28 | + |
| 29 | + // Store the computed result in dp to avoid redundant calculations in future recursive calls |
| 30 | + return dp[index][buy][limit] = profit; |
| 31 | + } |
| 32 | + |
| 33 | + // Main function to return the maximum profit |
| 34 | + int maxProfit(vector<int>& prices) { |
| 35 | + int n = prices.size(); |
| 36 | + |
| 37 | + // Create a 3D DP table initialized with -1, where: |
| 38 | + // dp[i][j][k] represents the maximum profit starting from index i, with a flag j (1 = can buy, 0 = can sell), |
| 39 | + // and k remaining transactions. |
| 40 | + vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(3, -1))); |
| 41 | + |
| 42 | + // Start the recursive function with index = 0, buy = 1 (indicating we can buy), and limit = 2 (two transactions allowed) |
| 43 | + return solve(prices, 0, 1, 2, dp); |
| 44 | + } |
| 45 | +}; |
0 commit comments