|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to solve the problem recursively with memoization |
| 4 | + // `money`: vector of amounts of money in each house |
| 5 | + // `n`: the current house index |
| 6 | + // `dp`: memoization array to store the maximum money for each house index |
| 7 | + int solve(vector<int>& money, int n, vector<int>& dp) { |
| 8 | + // Base case: if the index `n` is less than 0, return 0 (no money left to rob) |
| 9 | + if (n < 0) return 0; |
| 10 | + |
| 11 | + // Base case: if we are at the first house (index 0), return the money at this house |
| 12 | + if (n == 0) return money[0]; |
| 13 | + |
| 14 | + // If the result for this index `n` has already been calculated, return it from the `dp` array |
| 15 | + if (dp[n] != -1) return dp[n]; |
| 16 | + |
| 17 | + // Option 1: Rob this house, so skip the next one (move to house `n-2`) |
| 18 | + int include = solve(money, n - 2, dp) + money[n]; |
| 19 | + |
| 20 | + // Option 2: Skip this house, so move to the next house (house `n-1`) |
| 21 | + int exclude = solve(money, n - 1, dp) + 0; |
| 22 | + |
| 23 | + // Store the maximum of both choices in the memoization array `dp[n]` |
| 24 | + dp[n] = max(include, exclude); |
| 25 | + |
| 26 | + // Return the maximum money that can be robbed up to house `n` |
| 27 | + return dp[n]; |
| 28 | + } |
| 29 | + |
| 30 | + // Main function to calculate the maximum money that can be robbed |
| 31 | + int rob(vector<int>& nums) { |
| 32 | + int n = nums.size(); // Get the number of houses |
| 33 | + |
| 34 | + // Initialize the dp array with -1 (indicating uncalculated values) |
| 35 | + // dp[i] will store the maximum money that can be robbed from house 0 to house i |
| 36 | + vector<int> dp(n + 1, -1); |
| 37 | + |
| 38 | + // Call the helper function starting from the last house (index n-1) |
| 39 | + int maxMoney = solve(nums, n - 1, dp); |
| 40 | + |
| 41 | + // Return the maximum money that can be robbed |
| 42 | + return maxMoney; |
| 43 | + } |
| 44 | +}; |
0 commit comments