|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the maximum profit with transaction fee using dynamic programming (bottom-up approach) |
| 4 | + int solve(vector<int>& prices, int fee) { |
| 5 | + int n = prices.size(); // Get the size of the prices array |
| 6 | + |
| 7 | + // Initialize the dp array with 0, where dp[i][0] represents the maximum profit at index i without holding the stock |
| 8 | + // dp[i][1] represents the maximum profit at index i when holding the stock |
| 9 | + vector<vector<int>> dp(n+1, vector<int>(2, 0)); |
| 10 | + |
| 11 | + // Iterate backwards through the prices array starting from the last index |
| 12 | + for(int index = n-1; index >= 0; index--) { |
| 13 | + // Iterate through both possible states: buy (1) or sell (0) |
| 14 | + for(int buy = 0; buy <= 1; buy++) { |
| 15 | + |
| 16 | + int profit = 0; |
| 17 | + |
| 18 | + // If we are in a "buy" state (buy == 1), we have two options: |
| 19 | + // 1. Buy the stock at the current price (represented by -prices[index]) |
| 20 | + // and move to the next index where we are in a "sell" state (dp[index+1][0]). |
| 21 | + // 2. Do nothing and stay in the "buy" state at the next index (dp[index+1][1]). |
| 22 | + if(buy) { |
| 23 | + int buyStock = -prices[index] + dp[index+1][0]; // Buy stock |
| 24 | + int notBuyStock = 0 + dp[index+1][1]; // Do nothing (stay in the "buy" state) |
| 25 | + profit = max(buyStock, notBuyStock); // Take the maximum of these two options |
| 26 | + } else { |
| 27 | + // If we are in a "sell" state (buy == 0), we have two options: |
| 28 | + // 1. Sell the stock at the current price and subtract the fee (represented by +prices[index] - fee) |
| 29 | + // and move to the next index where we are in a "buy" state (dp[index+1][1]). |
| 30 | + // 2. Do nothing and stay in the "sell" state at the next index (dp[index+1][0]). |
| 31 | + int sellStock = +prices[index] - fee + dp[index+1][1]; // Sell stock and pay the fee |
| 32 | + int notSellStock = 0 + dp[index+1][0]; // Do nothing (stay in the "sell" state) |
| 33 | + profit = max(sellStock, notSellStock); // Take the maximum of these two options |
| 34 | + } |
| 35 | + |
| 36 | + // Store the calculated profit in the dp array |
| 37 | + dp[index][buy] = profit; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Return the maximum profit starting from index 0 with the possibility of buying the stock (buy = 1) |
| 42 | + return dp[0][1]; |
| 43 | + } |
| 44 | + |
| 45 | + // Main function to calculate the maximum profit with transaction fee |
| 46 | + int maxProfit(vector<int>& prices, int fee) { |
| 47 | + int n = prices.size(); // Get the size of the prices array |
| 48 | + return solve(prices, fee); // Call the solve function to calculate the maximum profit |
| 49 | + } |
| 50 | +}; |
0 commit comments