|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to calculate the maximum profit using an iterative dynamic programming approach |
| 4 | + int solve(vector<int>& prices) { |
| 5 | + |
| 6 | + int n = prices.size(); // Get the number of days |
| 7 | + |
| 8 | + // Create a 2D DP table to store the maximum profit for each state |
| 9 | + // dp[index][buy]: |
| 10 | + // - `index` represents the current day |
| 11 | + // - `buy` represents whether buying (1) or selling (0) is allowed on this day |
| 12 | + vector<vector<int>> dp(n + 1, vector<int>(2, 0)); |
| 13 | + |
| 14 | + // Base cases: No profit can be made after the last day |
| 15 | + dp[n][0] = 0; // No stock in hand, no profit |
| 16 | + dp[n][1] = 0; // Stock in hand, no profit |
| 17 | + |
| 18 | + // Iterate backward from the second last day to the first day |
| 19 | + for (int index = n - 1; index >= 0; index--) { |
| 20 | + // Iterate over the two states: buy (1) and sell (0) |
| 21 | + for (int buy = 0; buy <= 1; buy++) { |
| 22 | + int profit = 0; // Initialize profit for the current state |
| 23 | + |
| 24 | + if (buy) { |
| 25 | + // If we are allowed to buy: |
| 26 | + // - Option 1: Buy the stock today (-prices[index]) and move to the next day with buy=0 |
| 27 | + // - Option 2: Skip buying today and move to the next day with buy=1 |
| 28 | + int buyStock = -prices[index] + dp[index + 1][0]; |
| 29 | + int notBuyStock = 0 + dp[index + 1][1]; |
| 30 | + profit = max(buyStock, notBuyStock); |
| 31 | + } else { |
| 32 | + // If we are allowed to sell: |
| 33 | + // - Option 1: Sell the stock today (+prices[index]) and move to the next day with buy=1 |
| 34 | + // - Option 2: Skip selling today and move to the next day with buy=0 |
| 35 | + int sellStock = +prices[index] + dp[index + 1][1]; |
| 36 | + int notSellStock = 0 + dp[index + 1][0]; |
| 37 | + profit = max(sellStock, notSellStock); |
| 38 | + } |
| 39 | + |
| 40 | + // Store the profit for the current state in the DP table |
| 41 | + dp[index][buy] = profit; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // The maximum profit starting from day 0 with the ability to buy (buy=1) |
| 46 | + return dp[0][1]; |
| 47 | + } |
| 48 | + |
| 49 | + // Main function to calculate the maximum profit |
| 50 | + int maxProfit(vector<int>& prices) { |
| 51 | + return solve(prices); // Call the solve function |
| 52 | + } |
| 53 | +}; |
0 commit comments