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 0 and 2: 1 + 3 = 4, but they're circular neighbors so this is invalid. Instead, consider two scenarios: Scenario 1 [1,2,3]: best is 1+3=4. Scenario 2 [2,3,1]: best is max(2, 3) = 3. So answer is max(4,3) = 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
House Robber II - Circular Array Problem INPUT 2 House 0 3 House 1 2 House 2 Array (circular): 2 3 2 [0] [1] [2] First and Last are neighbors! Cannot rob both ALGORITHM STEPS 1 Break Circle Solve as 2 linear cases 2 Case A: Skip Last Rob houses [0 to n-2] 2 3 2 max=3 3 Case B: Skip First Rob houses [1 to n-1] 2 3 2 max=3 4 Take Maximum max(Case A, Case B) max(3, 3) = 3 FINAL RESULT Optimal Choice: Rob House 1 2 3 ROBBED 2 Maximum Loot: 3 OK - No Alert! No adjacent houses robbed Key Insight: Since houses form a circle, first and last houses are neighbors. We CANNOT rob both. Split into two linear problems: (1) houses[0..n-2] and (2) houses[1..n-1]. Return max of both. Each linear problem uses classic House Robber DP: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) TutorialsPoint - House Robber II | Optimal Solution - O(n) Time, O(1) Space
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
28.4K Views
High Frequency
~25 min Avg. Time
982 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen