House Robber II - Problem

You're a master thief planning the heist of a lifetime! This time, you've targeted a circular street where houses form a complete loop - meaning the first house is right next to the last house.

Each house contains a different amount of cash, represented by the array nums. However, there's a catch: the houses have a connected security system that will trigger an alarm if you rob any two adjacent houses on the same night.

Since the street is circular, you face an additional constraint: you cannot rob both the first AND last house, as they are neighbors!

Goal: Return the maximum amount of money you can steal without triggering the security system.

Example: Given houses [2,3,2] in a circle, you can rob house 2 (middle) for 3 total, but you cannot rob houses 1 and 3 together since house 1 and 3 are adjacent in the circle.

Input & Output

example_1.py โ€” Basic Circle
$ Input: [2,3,2]
โ€บ Output: 3
๐Ÿ’ก Note: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. Rob house 2 instead.
example_2.py โ€” Larger Circle
$ Input: [1,2,3,1]
โ€บ Output: 4
๐Ÿ’ก Note: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total = 1 + 3 = 4.
example_3.py โ€” Single House
$ Input: [5]
โ€บ Output: 5
๐Ÿ’ก Note: Only one house to rob, so rob it for maximum money of 5.

Visualization

Tap to expand
$2$3$2$1Adjacent!๐Ÿ’ก Split into two linear problems!
Understanding the Visualization
1
Identify the Constraint
The circular arrangement means first and last houses are adjacent
2
Create Two Scenarios
Scenario A: Include first house (exclude last). Scenario B: Include last house (exclude first)
3
Solve Linear Problems
Use standard house robber DP for each linear subarray
4
Take Maximum
Return the maximum result from both scenarios
Key Takeaway
๐ŸŽฏ Key Insight: The circular constraint creates exactly two mutually exclusive scenarios, each solvable as a linear house robber problem using dynamic programming.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^n)

We generate 2^n subsets and check each one

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Recursion stack depth and subset storage

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 0 โ‰ค nums[i] โ‰ค 1000
  • All houses are arranged in a circle
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
68.5K Views
High Frequency
~25 min Avg. Time
3.2K 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