House Robber

MediumDynamic Programming · 1-D DP🧩 1-D Dynamic ProgrammingLeetCode #198 ↗Updated

Problem

Houses stand in a row and nums[i] is the cash inside house i. A thief may rob any set of houses as long as no two chosen houses are adjacent (neighbouring break-ins trigger the alarm). Return the largest total the thief can collect.
Inputnums=[1,2,3,1]Output4 (houses 0 and 2)
Inputnums=[2,7,9,3,1]Output12 (houses 0, 2 and 4)
Inputnums=[2,1]Output2

1 ≤ n ≤ 100  ·  0 ≤ nums[i] ≤ 400

Try it yourself

Java
class Solution {
    public int rob(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
At house i there are only two choices: skip it (keep the best up to i-1) or rob it (its cash + the best up to i-2). So best(i) = max(best(i-1), best(i-2) + nums[i]) — and only the last two values are ever needed.
Pattern1-D Dynamic Programming

Instinct The best answer at position i depends only on a few earlier positions (i-1, i-2, ...) - write dp[i] from its predecessors, then roll it into variables.

Memory hack Look back, pick best, roll forward - every step only remembers the last couple of stairs it stood on.

Open the 1-D Dynamic Programming guide →

Approaches

Brute ForcePlain Recursion (Rob or Skip)

Time O(2n)Space O(n)

rob(i) = best total from houses i..n-1. Either skip house i (rob(i+1)) or take it and jump past its neighbour (nums[i] + rob(i+2)). The same subproblems are recomputed over and over, like naive Fibonacci.

Java
public int rob(int[] nums) {
    return best(nums, 0);
}

private int best(int[] nums, int i) {
    if (i >= nums.length) return 0;
    int skip = best(nums, i + 1);
    int take = nums[i] + best(nums, i + 2);
    return Math.max(skip, take);
}

Directly mirrors the choice, but the call tree grows exponentially.

At a glance

LevelApproachTimeSpace
Brute ForcePlain Recursion (Rob or Skip)O(2n)O(n)
BetterBottom-Up DP TableO(n)O(n)
OptimalTwo Rolling VariablesO(n)O(1)
Common pitfalls
  • Taking all even or all odd indices — the best set can skip two houses in a row.
  • Off-by-one in the table version: dp[i] refers to nums[i-1].
  • Updating prev before computing the new value — overwrites data you still need.
Interview tips
  • State the rob/skip choice first; the recurrence then writes itself.
  • Go recursion → memo/table → two variables, naming each complexity.
  • Mention the circular variant (House Robber II): run the linear solution twice.
Pattern
1-D DP, take-or-skip → choose items in a line where taking one blocks its neighbour.
My notes saved in this browser