102. House Robber II
View on NeetCode
View on LeetCode
Problem
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
Example 2:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 3:
Input: nums = [1,2,3]
Output: 3
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 1000
Solution
Approach: Two Passes of House Robber I
The key insight is that since houses are circular, we can’t rob both the first and last house. So we solve two subproblems: rob houses 0 to n-2, or rob houses 1 to n-1, then take the maximum.
Implementation
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums)
def rob_linear(houses):
rob1, rob2 = 0, 0
for house in houses:
new_rob = max(rob2, rob1 + house)
rob1 = rob2
rob2 = new_rob
return rob2
# Case 1: Rob houses 0 to n-2 (exclude last house)
# Case 2: Rob houses 1 to n-1 (exclude first house)
return max(rob_linear(nums[:-1]), rob_linear(nums[1:]))
Alternative Implementation (More Explicit)
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
if n == 2:
return max(nums)
def rob_range(start, end):
prev2 = 0
prev1 = 0
for i in range(start, end):
current = max(prev1, prev2 + nums[i])
prev2 = prev1
prev1 = current
return prev1
# Rob houses 0 to n-2, or houses 1 to n-1
return max(rob_range(0, n-1), rob_range(1, n))
Complexity Analysis
- Time Complexity: O(n), where n is the number of houses. We make two linear passes.
- Space Complexity: O(1), only using constant extra space.
Key Insights
-
Circular Constraint: The circular arrangement means robbing house 0 excludes house n-1 and vice versa.
- Break the Circle: We can break the circle by considering two scenarios:
- Exclude the last house (rob 0 to n-2)
- Exclude the first house (rob 1 to n-1)
-
Reuse House Robber I: Each scenario reduces to the linear House Robber problem.
-
Take Maximum: The answer is the maximum of these two scenarios.
- Edge Cases:
- Single house: rob it
- Two houses: rob the one with more money
- Both edge cases avoid the circular constraint issue
- No Overlap: The two ranges don’t overlap in a way that causes issues - we simply solve each independently.