|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the maximum profit using dynamic programming with space optimization |
| 4 | + int solve(vector<int>& prices){ |
| 5 | + int n = prices.size(); |
| 6 | + |
| 7 | + // Initialize two 2D vectors: 'curr' to store the current results and 'next' for the next day's results |
| 8 | + // 'curr' and 'next' are of size 2 (buy/sell) and 3 (transaction limits 1 and 2). |
| 9 | + vector<vector<int>> curr(2, vector<int>(3, 0)); |
| 10 | + vector<vector<int>> next(2, vector<int>(3, 0)); |
| 11 | + |
| 12 | + // Start iterating from the last day (index = n-1) to the first day (index = 0) |
| 13 | + for(int index = n-1; index >= 0; index--){ |
| 14 | + // For each index, check if we can buy (buy == 1) or sell (buy == 0), and the remaining transaction limit |
| 15 | + for(int buy = 0; buy <= 1; buy++){ |
| 16 | + for(int limit = 1; limit <= 2; limit++){ |
| 17 | + int profit = 0; |
| 18 | + |
| 19 | + // If we can buy (buy == 1) |
| 20 | + if(buy){ |
| 21 | + // Option 1: Buy the stock today, and move to the next day with the ability to sell and the same remaining transaction limit |
| 22 | + int buyStock = -prices[index] + next[0][limit]; |
| 23 | + // Option 2: Skip buying and move to the next day, still with the ability to buy and the same remaining transaction limit |
| 24 | + int notBuyStock = 0 + next[1][limit]; |
| 25 | + // Choose the option that gives the maximum profit |
| 26 | + profit = max(buyStock, notBuyStock); |
| 27 | + }else{ |
| 28 | + // If we can sell (buy == 0) |
| 29 | + // Option 1: Sell the stock today, reduce the transaction limit by 1, and move to the next day with the ability to buy |
| 30 | + int sellStock = +prices[index] + next[1][limit-1]; |
| 31 | + // Option 2: Skip selling and move to the next day, still with the ability to sell and the same remaining transaction limit |
| 32 | + int notSellStock = 0 + next[0][limit]; |
| 33 | + // Choose the option that gives the maximum profit |
| 34 | + profit = max(sellStock, notSellStock); |
| 35 | + } |
| 36 | + |
| 37 | + // Store the computed result for the current index, buy/sell option, and transaction limit in the 'curr' vector |
| 38 | + curr[buy][limit] = profit; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // After processing the current index, move the results of 'curr' to 'next' for the next iteration |
| 43 | + next = curr; |
| 44 | + } |
| 45 | + |
| 46 | + // The final result is stored at curr[1][2], representing the maximum profit starting from day 0, |
| 47 | + // with the ability to buy and 2 transactions allowed. |
| 48 | + return curr[1][2]; |
| 49 | + } |
| 50 | + |
| 51 | + // Main function to return the maximum profit from the given prices array |
| 52 | + int maxProfit(vector<int>& prices) { |
| 53 | + // Call the solve function and return the result |
| 54 | + return solve(prices); |
| 55 | + } |
| 56 | +}; |
0 commit comments