House Robber

Medium

Topics
ArrayDynamic Programming

You are a robber planning to rob houses along a street. You cannot rob two adjacent houses. Given nums (money in each house), return the maximum you can rob without alerting the police.

Example 1

10213213
robbed
The shaded houses total 4 and no two are adjacent. At each house the choice is only between taking it plus the best up to two back, or skipping it and keeping the best up to one back — so two running numbers replace the whole table.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,3,1]
Output: 4

Example 2

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

Constraints

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

Intuition

At each house you make a binary choice: rob it (then you could not have robbed the previous one) or skip it. The best total up to house i is max(skip = best up to i-1, rob = best up to i-2 + money[i]).

Approach

  1. Keep two rolling values: best up to the previous house and the house before that.
  2. For each house: new = max(prev, prevPrev + money).
  3. Roll forward; the last value is the answer.

Walkthrough

nums = [2, 7, 9, 3, 1]
cur: 2, 7, 11, 11, 12  -> answer 12  (2 + 9 + 1)

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two rolling variables instead of a DP array.

Common Pitfalls

  • The choice is max(cur, prev + x) -- skip this house, or rob it and add the best up to two houses back. Using prev on both sides drops the skip option, and [1,2,3,1] returns 3 instead of 4.
  • The simultaneous assignment matters. Updating prev before computing the new cur feeds the new value back into its own formula, which quietly allows robbing adjacent houses.

Full Solution — all languages

class Solution:
    def rob(self, nums):
        prev, cur = 0, 0
        for x in nums:
            prev, cur = cur, max(cur, prev + x)
        return cur
SensAI
Beta
Tap the mic to stop voice mode