|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to solve the problem using dynamic programming (optimized space approach) |
| 4 | + // `money`: vector containing the amounts of money in each house |
| 5 | + // `n`: the number of houses |
| 6 | + int solve(vector<int>& money, int n) { |
| 7 | + // Base cases: |
| 8 | + // prev2 represents the maximum money robbed from houses up to index 0 |
| 9 | + // prev1 represents the maximum money robbed from houses up to index 1 |
| 10 | + int prev2 = money[0]; // Only one house, so rob it |
| 11 | + int prev1 = max(money[0], money[1]); // Take the maximum of robbing the first or second house |
| 12 | + |
| 13 | + // Iterate through the remaining houses starting from index 2 |
| 14 | + for (int i = 2; i < n; i++) { |
| 15 | + // Option 1: Rob the current house (house i), and add money from house i to the result of robbing house i-2 (prev2) |
| 16 | + int include = prev2 + money[i]; |
| 17 | + |
| 18 | + // Option 2: Skip the current house (house i), and keep the maximum from the previous house (prev1) |
| 19 | + int exclude = prev1 + 0; |
| 20 | + |
| 21 | + // Calculate the maximum money we can rob up to house i by choosing either to include or exclude house i |
| 22 | + int current = max(include, exclude); |
| 23 | + |
| 24 | + // Update prev2 and prev1 for the next iteration |
| 25 | + prev2 = prev1; // Move prev1 to prev2 (we are shifting one step to the right) |
| 26 | + prev1 = current; // Update prev1 to be the maximum of robbing up to house i |
| 27 | + } |
| 28 | + |
| 29 | + // After iterating through all houses, prev1 will hold the maximum money that can be robbed |
| 30 | + return prev1; |
| 31 | + } |
| 32 | + |
| 33 | + // Main function to start solving the problem |
| 34 | + int rob(vector<int>& nums) { |
| 35 | + int n = nums.size(); // Get the number of houses |
| 36 | + |
| 37 | + // Handle edge cases where there are no houses or only one house |
| 38 | + if (n == 0) return 0; // No houses to rob |
| 39 | + if (n == 1) return nums[0]; // Only one house to rob, return its value |
| 40 | + |
| 41 | + // Call the helper function to calculate the maximum money that can be robbed |
| 42 | + return solve(nums, n); |
| 43 | + } |
| 44 | +}; |
0 commit comments