House Robber II - 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.
Input & Output
Example 1 — Basic Circular Case
$
Input:
nums = [2,3,2]
›
Output:
3
💡 Note:
You cannot rob house 0 and 2 (circular neighbors), so rob house 1 with value 3.
Example 2 — Larger Circle
$
Input:
nums = [1,2,3,1]
›
Output:
4
💡 Note:
Rob houses 1 and 3: 2 + 2 = 4 (wait, that's wrong). Actually rob houses 0 and 2: 1 + 3 = 4, but they're circular neighbors. So rob houses 1 and 2 is invalid (adjacent). Best is rob house 2 only for 3. Wait - let me recalculate: Scenario 1 [1,2,3]: best is 1+3=4. Scenario 2 [2,3,1]: best is 2+1=3. So answer is 4.
Example 3 — Single House
$
Input:
nums = [5]
›
Output:
5
💡 Note:
Only one house to rob, return its value.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Circular Setup
Houses arranged in circle with values [2,3,2]
2
Adjacent Constraint
Cannot rob adjacent houses (including first-last)
3
Optimal Solution
Rob house 1 with value 3
Key Takeaway
🎯 Key Insight: Transform the circular problem into two linear problems by excluding either the first or last house.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code