Problem Description
Given an integer array representing the amount of money at each house, determine the maximum amount you can rob without triggering the security system, which is activated if two adjacent houses are robbed.
Key Insights
- The problem can be solved using Dynamic Programming.
- For each house, decide whether to rob it or not.
- Recurrence relation: dp[i] = max(dp[i-1], dp[i-2] + currentHouseMoney)
- Use iterative computation to keep track of the optimal solutions without needing extra space for the entire dp array.
Space and Time Complexity
Time Complexity: O(n), where n is the number of houses. Space Complexity: O(1), using only two variables to track the previous decisions.
Solution
We use a dynamic programming approach by iterating through each house in the array. At each step, we consider two scenarios: either we rob the current house (and add its money to the total from two houses ago) or we skip it (keeping the optimal solution up to the previous house). By using two variables to store these intermediate results, we achieve an optimized space complexity of O(1).