Skip to main content
50

House Robber

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

You're planning to rob houses along a street. nums[i] is the amount of money in house i. Neighboring houses share an alarm system: robbing two adjacent houses sets it off.

Return the maximum amount you can rob without robbing two adjacent houses.

Understand the problem

  • Adjacent means next to each other: houses 2 and 3 are adjacent; houses 2 and 4 are not.
  • You can rob any set of houses, as long as no two of them are neighbors.
  • You want the largest possible total.

Example 1

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

Rob houses 0 and 2: 1 + 3 = 4.

Example 2

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

Rob houses 0, 2 and 4: 2 + 9 + 1 = 12.

Example 3

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

Rob the first and the last: 2 + 2 = 4. Note that "every other house" (2 + 1 = 3) isn't the best here.

Constraints

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

Hints

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

    The idea in one sentence

    Walk the street keeping "the best total so far"; at each house, either skip it (keep the previous best) or rob it (its money plus the best from two houses back), whichever is larger.

    Why simple strategies fail

    It's tempting to use a simple rule (this is called a greedy strategy: always take what looks best right now):

    • "Rob every other house": on [2, 1, 1, 2] this gives 2 + 1 = 3, but the answer is 4 (first and last).
    • "Always rob the richest house left": on [2, 3, 2] this takes 3 alone, but 2 + 2 = 4 is better.

    The trouble is that each choice affects which houses are allowed later. We need to consider both options at every house, without trying every combination.

    The key insight

    Walk the street left to right, and define:

    best(i) = the most money you can rob from houses 0 to i.

    At house i, you have exactly two choices:

    • Skip house i: the best total is whatever was best up to house i - 1: best(i - 1).
    • Rob house i: you get nums[i], but then house i - 1 must be skipped, so you add the best up to house i - 2: best(i - 2) + nums[i].

    Take whichever is bigger:

    text
    best(i) = max(best(i - 1), best(i - 2) + nums[i])

    Exactly like Climbing Stairs, each value only needs the previous two, so two variables are enough: prev = best(i - 1) and prevPrev = best(i - 2), both starting at 0 (no houses, no money).

    Step by step

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

    HouseMoneySkip it (prev)Rob it (prevPrev + money)bestAfter: prevPrev, prev
    0200 + 2 = 220, 2
    1720 + 7 = 772, 7
    2972 + 9 = 11117, 11
    33117 + 3 = 101111, 11
    411111 + 1 = 121211, 12

    Answer: 12 (houses 0, 2 and 4).

    The code

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

    How fast is it?

    • Time: O(n). One pass over the houses.
    • Memory: O(1). Two variables.

    Common mistakes

    • Using a greedy rule like "every other house". Correct on some inputs, wrong on others.
    • Adding nums[i] to prev instead of prevPrev. That would rob two neighbors.
    • Updating the variables in the wrong order, so the new prev is computed from an already-updated prevPrev. Update both at once, or use a temporary variable.

    Going deeper

    • House Robber II puts the houses in a circle, so the first and last are neighbors too. The trick is to run this exact solution twice.
    • "At each position, choose between taking it or skipping it, based on the best answers so far" is one of the most common DP shapes. You'll see it in Decode Ways and Coin Change too.

    Reference solution

    js
    /**
     * @param {number[]} nums
     * @return {number}
     */
    export default function rob(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 (keep prev), or rob it (amount + best from two houses back).
        // Then slide forward: the old prev becomes prevPrev. Both updated at once.
        ;[prevPrev, prev] = [prev, Math.max(prev, prevPrev + amount)]
      }
      return prev
    }
    ts
    export default function rob(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 (keep prev), or rob it (amount + best from two houses back).
        // Then slide forward: the old prev becomes prevPrev. Both updated at once.
        ;[prevPrev, prev] = [prev, Math.max(prev, prevPrev + amount)]
      }
      return prev
    }
    python
    def rob(nums: list[int]) -> int:
        # prev_prev: best total up to two houses back. prev: best up to the previous house.
        prev_prev, prev = 0, 0
        for amount in nums:
            # Skip this house (keep prev), or rob it (amount + best from two houses back).
            # Then slide forward: the old prev becomes prev_prev. Both updated at once.
            prev_prev, prev = prev, max(prev, prev_prev + amount)
        return prev