|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive helper function to calculate the maximum profit |
| 4 | + // `prices`: vector of stock prices |
| 5 | + // `index`: current day index in the prices array |
| 6 | + // `buy`: indicates whether we are allowed to buy (1) or need to sell (0) |
| 7 | + // `k`: remaining transactions we are allowed to perform |
| 8 | + // `dp`: 3D DP table to store intermediate results for memoization |
| 9 | + int solve(vector<int>& prices, int index, int buy, int k, vector<vector<vector<int>>>& dp) { |
| 10 | + int n = prices.size(); // Total number of days in the prices array |
| 11 | + |
| 12 | + // Base case: If we reach the end of the array or have no transactions left, return 0 |
| 13 | + if(index == n || k == 0) return 0; |
| 14 | + |
| 15 | + // If the current state is already computed, return the stored value |
| 16 | + if(dp[index][buy][k] != -1) return dp[index][buy][k]; |
| 17 | + |
| 18 | + int profit = 0; // Variable to store the maximum profit at the current state |
| 19 | + |
| 20 | + if(buy) { |
| 21 | + // If we are allowed to buy, we have two choices: |
| 22 | + // 1. Buy the stock on this day and subtract its price from profit, then move to the next day with `buy = 0`. |
| 23 | + // 2. Skip buying and move to the next day with `buy = 1`. |
| 24 | + profit = max( |
| 25 | + -prices[index] + solve(prices, index + 1, 0, k, dp), // Buy |
| 26 | + 0 + solve(prices, index + 1, 1, k, dp) // Skip |
| 27 | + ); |
| 28 | + } else { |
| 29 | + // If we are not allowed to buy (we need to sell), we have two choices: |
| 30 | + // 1. Sell the stock on this day and add its price to profit, then move to the next day with `buy = 1` and decrement transactions. |
| 31 | + // 2. Skip selling and move to the next day with `buy = 0`. |
| 32 | + profit = max( |
| 33 | + prices[index] + solve(prices, index + 1, 1, k - 1, dp), // Sell |
| 34 | + 0 + solve(prices, index + 1, 0, k, dp) // Skip |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + // Store the result in the DP table for future use and return it |
| 39 | + return dp[index][buy][k] = profit; |
| 40 | + } |
| 41 | + |
| 42 | + // Main function to calculate the maximum profit |
| 43 | + // `k`: maximum number of transactions allowed |
| 44 | + // `prices`: vector of stock prices |
| 45 | + int maxProfit(int k, vector<int>& prices) { |
| 46 | + int n = prices.size(); // Total number of days |
| 47 | + |
| 48 | + // Initialize a 3D DP table with dimensions [n][2][k+1] and set all values to -1 |
| 49 | + // dp[i][j][l]: maximum profit at day `i` with `j` (buy = 1, sell = 0) and `l` transactions remaining |
| 50 | + vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(k + 1, -1))); |
| 51 | + |
| 52 | + // Start the recursive process from day 0, with the ability to buy and `k` transactions remaining |
| 53 | + return solve(prices, 0, 1, k, dp); |
| 54 | + } |
| 55 | +}; |
0 commit comments