|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the maximum profit using recursion. |
| 4 | + // Parameters: |
| 5 | + // prices - reference to the price array |
| 6 | + // index - current day we are processing |
| 7 | + // buy - whether we are allowed to buy (1) or sell (0) on the current day |
| 8 | + int solve(vector<int>& prices, int index, int buy) { |
| 9 | + // Base case: If we have processed all the days, there is no profit to be made |
| 10 | + if (index == prices.size()) return 0; |
| 11 | + |
| 12 | + int profit = 0; // Initialize profit for the current state |
| 13 | + |
| 14 | + if (buy) { |
| 15 | + // If we are allowed to buy on this day, we have two choices: |
| 16 | + // 1. Buy the stock today: Subtract prices[index] and move to the next day with buy=0 (since we now own the stock). |
| 17 | + // 2. Skip buying today: Move to the next day and keep buy=1. |
| 18 | + profit = max( |
| 19 | + (-prices[index] + solve(prices, index + 1, 0)), // Option 1: Buy today |
| 20 | + (0 + solve(prices, index + 1, 1)) // Option 2: Skip buying |
| 21 | + ); |
| 22 | + } else { |
| 23 | + // If we are allowed to sell on this day, we have two choices: |
| 24 | + // 1. Sell the stock today: Add prices[index] to profit and move to the next day with buy=1 (since we no longer own the stock). |
| 25 | + // 2. Skip selling today: Move to the next day and keep buy=0. |
| 26 | + profit = max( |
| 27 | + (+prices[index] + solve(prices, index + 1, 1)), // Option 1: Sell today |
| 28 | + (0 + solve(prices, index + 1, 0)) // Option 2: Skip selling |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | + // Return the maximum profit for the current state |
| 33 | + return profit; |
| 34 | + } |
| 35 | + |
| 36 | + // Main function to calculate the maximum profit |
| 37 | + int maxProfit(vector<int>& prices) { |
| 38 | + // Start from the first day (index=0) with the ability to buy (buy=1) |
| 39 | + return solve(prices, 0, 1); |
| 40 | + } |
| 41 | +}; |
0 commit comments