Problem Description
A robber wants to steal from houses arranged in a circle. Each house has a certain amount of money, but robbing two adjacent houses will trigger the security system. Given an array of non-negative integers representing the money in each house, determine the maximum amount of money that can be robbed without alerting the police.
Key Insights
- The houses are arranged in a circle, meaning the first and last houses are neighbors.
- Because of the circular arrangement, you cannot rob both the first and last houses.
- The problem can be reduced into two separate linear House Robber problems:
- One considering houses from index 1 to n-1 (exclude the first house).
- The other considering houses from index 0 to n-2 (exclude the last house).
- Use dynamic programming with constant space (using two variables) to compute the solution for a linear array of houses.
Space and Time Complexity
Time Complexity: O(n), where n is the number of houses. Space Complexity: O(1), as only a constant amount of extra space is used.
Solution
To handle the circular dependency, we solve two linear versions of the problem:
- Exclude the first house and calculate the maximum rob amount for houses from index 1 to n-1.
- Exclude the last house and calculate the maximum rob amount for houses from index 0 to n-2. Then, the final answer is the maximum of these two calculated values. We use dynamic programming by iterating through the list and at each step, calculating the maximum money that can be robbed up to that point with two variables.