Skip to main content
51

House Robber II

Mediumdynamic programming

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

The same robbery as House Robber, but now the houses stand in a circle: the first house and the last house are neighbors. Robbing two adjacent houses still sets off the alarm.

Given nums, the money in each house, return the maximum you can rob.

Understand the problem

  • Everything from House Robber still applies: no two neighboring houses.
  • The only change: house 0 and house n - 1 are now neighbors too, so you can't rob both of them.
  • If you haven't solved House Robber yet, start there: this problem reuses it.

Example 1

text
Input:  nums = [2, 3, 2]
Output: 3

On a straight street, 2 + 2 = 4 would be best. But in a circle, houses 0 and 2 are neighbors, so the best is house 1 alone: 3.

Example 2

text
Input:  nums = [1, 2, 3, 1]
Output: 4

Houses 0 and 2: 1 + 3 = 4. They aren't neighbors, even in a circle.

Example 3

text
Input:  nums = [1, 2, 3]
Output: 3

Every pair of houses is adjacent in a circle of three, so you can rob only one: the 3.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    The circle only forbids robbing both the first and the last house, so solve the straight-street problem twice (once without the first house, once without the last) and take the better answer.

    The key insight: break the circle

    Compared with House Robber, the circle adds exactly one rule: the first and the last house can't both be robbed.

    So every valid plan falls into at least one of two cases:

    • The first house isn't robbed. Then it's as if it doesn't exist, and the rest is a straight street: nums[1..n-1].
    • The last house isn't robbed. Then the rest is the straight street nums[0..n-2].

    (A plan that skips both fits either case, which is fine.) Each case is a plain House Robber problem, which you already know how to solve. Solve both and return the larger answer.

    text
    circle:           [2, 3, 2]      (house 0 and house 2 are neighbors)
    skip the first:   [3, 2]         → best 3
    skip the last:    [2, 3]         → best 3
    answer:           max(3, 3) = 3

    One special case: a single house. Both "lines" would be empty (best 0), but there's no neighbor to worry about, so you can rob it: return nums[0].

    Step by step

    nums = [1, 2, 3, 1]:

    Without the first house: [2, 3, 1]

    House moneySkip (prev)Rob (prevPrev + money)best
    200 + 2 = 22
    320 + 3 = 33
    132 + 1 = 33

    Without the last house: [1, 2, 3]

    House moneySkip (prev)Rob (prevPrev + money)best
    100 + 1 = 11
    210 + 2 = 22
    321 + 3 = 44

    Answer: max(3, 4) = 4.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Two passes over the houses.
    • Memory: O(n) for the two slices, as written. (You can avoid copying by passing start and end indexes to the helper instead, for O(1).)

    Common mistakes

    • Forgetting the single-house case. Both slices are empty, and you'd return 0 instead of nums[0].
    • Trying to track "did I rob the first house?" inside one pass. It can be done, but splitting into two plain problems is much simpler and less error-prone.

    Going deeper

    "Break a circle into two straight lines" is a general trick for circular arrays: decide one thing about the "wrap-around" point (here, which end to leave out), and each case becomes a problem you already know.

    Reference solution

    js
    // House Robber on a straight street (see that problem).
    function robLine(nums) {
      let prevPrev = 0 // best total up to two houses back
      let prev = 0 // best total up to the previous house
      for (const amount of nums) {
        // Skip this house, or rob it plus the best from two houses back.
        ;[prevPrev, prev] = [prev, Math.max(prev, prevPrev + amount)]
      }
      return prev
    }
    
    /**
     * @param {number[]} nums
     * @return {number}
     */
    export default function rob(nums) {
      // One house has no neighbors at all: just rob it.
      if (nums.length === 1) return nums[0]
      // The first and last can't both be robbed, so leave one of them out each time.
      return Math.max(robLine(nums.slice(1)), robLine(nums.slice(0, -1)))
    }
    ts
    // House Robber on a straight street (see that problem).
    function robLine(nums: number[]): number {
      let prevPrev = 0 // best total up to two houses back
      let prev = 0 // best total up to the previous house
      for (const amount of nums) {
        // Skip this house, or rob it plus the best from two houses back.
        ;[prevPrev, prev] = [prev, Math.max(prev, prevPrev + amount)]
      }
      return prev
    }
    
    export default function rob(nums: number[]): number {
      // One house has no neighbors at all: just rob it.
      if (nums.length === 1) return nums[0]
      // The first and last can't both be robbed, so leave one of them out each time.
      return Math.max(robLine(nums.slice(1)), robLine(nums.slice(0, -1)))
    }
    python
    def rob_line(nums: list[int]) -> int:
        # House Robber on a straight street (see that problem).
        prev_prev, prev = 0, 0  # best totals up to two houses back / the previous house
        for amount in nums:
            # Skip this house, or rob it plus the best from two houses back.
            prev_prev, prev = prev, max(prev, prev_prev + amount)
        return prev
    
    
    def rob(nums: list[int]) -> int:
        # One house has no neighbors at all: just rob it.
        if len(nums) == 1:
            return nums[0]
        # The first and last can't both be robbed, so leave one of them out each time.
        return max(rob_line(nums[1:]), rob_line(nums[:-1]))