AceYourInterviews
Checking sign-in…

129. House Robber II

IntermediateBreak a cycle into two overlapping path-DP cases

Choose houses with the largest possible total while avoiding adjacent selected houses. In this version, the end of the street connects back to its beginning.

When at least two houses exist, the first and last houses are neighbors. Handle the single-house case separately according to the contract.

Example 1

Input

nums=[2,3,2]

Output

3

Explanation: The two endpoint 2s are neighbors on the circle. The linear answer 4 is invalid here.

Example 2

Input

nums=[1,2,3,1]

Output

4

Explanation: Take indices 0 and 2. The case excluding the last house achieves 4; excluding the first achieves 3.

Example 3

Input

nums=[10,1,1,10]

Output

11

Explanation: The linear endpoint total 20 is forbidden; choose one endpoint and the nonadjacent interior house.

Example 4

Input

nums=[7]

Output

7

Explanation: The explicit singleton convention avoids excluding the only house in both range cases.

Constraints

  • 0 <= nums.length <= 105
  • 0 <= nums[i] <= 231 - 1
Hints
Hint 1

What single pair of indices makes the circular version differ from the linear one?

Hint 2

Every feasible solution excludes at least one endpoint. Can each exclusion leave a path?

Hint 3

Handle n≤1 explicitly, then return max(rob range [0,n−1), rob range [1,n)) with fresh rolling registers.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Circular endpoints cannot combine

[2,3,2]
3