← Back to DSA
#198

House Robber

House Robber solution for LeetCode 198, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.

Medium
ArrayDynamic Programming
Solve on LeetCode ↗

House Robber

Why it belongs on this sheet

This is one of the most reusable DP patterns: at each position, either take the current option or skip it.

Pattern

Take or skip

Approach

For each house, the best answer is either the previous best without this house, or the best up to two houses back plus this house's money.

Java solution

class Solution {
  public int rob(int[] nums) {
    int robPrev = 0;
    int skipPrev = 0;

    for (int num : nums) {
      int newRob = skipPrev + num;
      skipPrev = Math.max(skipPrev, robPrev);
      robPrev = newRob;
    }

    return Math.max(robPrev, skipPrev);
  }
}

Complexity

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

Interview note

If the variable names feel abstract, phrase it as "best including current" and "best excluding current."

Dynamic Programming

7 DP Patterns > 100 LeetCode Questions

Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.

7 patternsProgress tracking
Read 7 patterns (5 min)