House Robber

Medium Dynamic Programming

Problem

You're a thief planning to rob houses along a street. Each house has some money, but you can't rob two adjacent houses without triggering an alarm. Return the max money you can rob.

Example 1 Input: nums = [1,2,3,1] Output: 4 Explain: Rob houses 0 and 2 (1+3).
Example 2 Input: nums = [2,7,9,3,1] Output: 12 Explain: Rob 0, 2, 4 (2+9+1).
Example 3 Input: nums = [2,1,1,2] Output: 4 Explain: Rob 0 and 3.

Constraints

Approach — Dynamic Programming

This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) to O(n²) time.

Solution code

Python

class Solution:
    def rob(self, nums):
        prev = cur = 0
        for x in nums:
            prev, cur = cur, max(cur, prev + x)
        return cur

Java

class Solution {
    public int rob(int[] nums) {
        int prev = 0, curr = 0;
        for (int n : nums) {
            int next = Math.max(curr, prev + n);
            prev = curr;
            curr = next;
        }
        return curr;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve House Robber interactively → ← All solutions