← DSA
MEDIUM

House Robber

PracticeNeetCode ↗LeetCode ↗

Houses are lined up in a row, each holding some amount of money in nums. You can't rob two adjacent houses (it trips the alarm). Return the most money you can rob without robbing two neighbors.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Initialize rob1 = 0 (best total two houses back) and rob2 = 0 (best total through the previous house).
  2. For each house value n: compute current = max(n + rob1, rob2) — either rob this house plus the best total from two houses back, or skip it and keep the best total through the previous house.
  3. Shift forward: rob1 becomes the old rob2, rob2 becomes current.
  4. After every house is processed, rob2 holds the answer.

Complexity

Time: O(n) — Space: O(1)

Code

def rob(nums: list[int]) -> int:
    rob1, rob2 = 0, 0
    for n in nums:
        rob1, rob2 = rob2, max(n + rob1, rob2)
    return rob2

Code Explanation

How the solution above works, piece by piece.

  1. At each house choose: rob it (add its money to the best total from two houses back, since neighbours can't both be robbed) or skip it (keep the best total from the previous house).
  2. rob1 = best total up to two houses back, rob2 = best total up to the previous house.
  3. rob1, rob2 = rob2, max(n + rob1, rob2) computes the new best and shifts the window in one step.
  4. After the last house, rob2 is the answer.
  5. O(n) time, O(1) space.

Visual Walkthrough

Running it on nums = [1, 2, 3, 1]:

trace10213213house 0rob it: 1 + 0 = 1 vs skip: 0 → best 11231house 1rob it: 2 + 0 = 2 vs skip: 1 → best 21231house 2rob it: 3 + 1 = 4 vs skip: 2 → best 41231house 3rob it: 1 + 2 = 3 vs skip: 4 → best 4
Robbing houses 0 and 2 (1 + 3 = 4) beats every other non-adjacent choice. The running best becomes 1, 2, 4, 4.
current house

Video Explanation

NeetCode — Dynamic Programming, LeetCode 198