House Robber II

Medium

Topics
ArrayDynamic Programming

Same as House Robber, but the houses are arranged in a circle — the first and last are adjacent. Return the maximum you can rob.

Example 1

203122
robbedthe two ends, which are neighbours
The houses stand in a circle, so the first and last are next to each other and cannot both be taken — that is the only difference from the straight-line version. The shaded houses total 3, and no two of them are adjacent.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [2,3,2]
Output: 3

Example 2

10213213
robbedthe two ends, which are neighbours
Input:  nums = [1,2,3,1]
Output: 4

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

The houses form a circle, so the first and last are neighbors and cannot both be robbed. That single constraint splits the problem into two linear House Robber problems.

Solve once excluding the first house and once excluding the last; the better of the two is the answer.

Approach

  1. Handle the single-house case directly.
  2. Run linear House Robber on nums[1:] (drop the first).
  3. Run it on nums[:-1] (drop the last).
  4. Return the maximum.

Walkthrough

nums = [2, 3, 2]
exclude first -> rob [3,2] -> 3
exclude last  -> rob [2,3] -> 3
max -> 3

Complexity

  • Time — O(n): two linear passes.
  • Space — O(1): rolling variables.

Common Pitfalls

  • A single house needs its own case. Both ranges are empty when len(nums) == 1 -- line(0, 0) and line(1, 1) -- so the answer comes back 0 instead of the only house's value.
  • Running one pass over the whole array ignores the circle entirely and lets you rob both ends: [2,3,2] returns 4 instead of 3. The two passes exist precisely to forbid first-and-last together.

Full Solution — all languages

class Solution:
    def rob(self, nums):
        def line(start, end):
            prev = cur = 0
            for i in range(start, end):
                prev, cur = cur, max(cur, prev + nums[i])
            return cur
        if len(nums) == 1:
            return nums[0]
        # Index ranges rather than nums[:-1] and nums[1:]. Both slices copy n-1
        # elements, which would make this O(n) space instead of the O(1) claimed.
        return max(line(0, len(nums) - 1), line(1, len(nums)))
Asked at Databricks Nutanix
SensAI
Beta
Tap the mic to stop voice mode