Command Palette

Search for a command to run...

Problem 28.3 · DP Foundations: 1DMedium

House Robber

What it teaches: Take-or-skip: dp[i] = max(dp[i − 1], dp[i − 2] + nums[i]).

Practise it on judges as “House Robber”.

The problem

Rob houses along a street for the most money without robbing two adjacent houses.

Example 1

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

Constraints

  • 1 ≤ n ≤ 100

Pattern clues in the wording

  • → Choosing an item forbids its neighbour
  • → Maximise a sum

These clues point to 1D Dynamic Programming: Define dp[i] as the answer for the first i items, write how it depends on smaller i, and fill it left to right.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int rob(int[] nums) {
        return 0;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
nums = [1,2,3,1]
4
2
nums = [2,7,9,3,1]
12

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Rolling take/skip

Time O(n) Space O(1)

prev2, prev1; cur = max(prev1, prev2 + x).

Approach 1
class Solution {
    public int rob(int[] nums) {
        int prev2 = 0, prev1 = 0;
        for (int x : nums) {
            int cur = Math.max(prev1, prev2 + x);
            prev2 = prev1;
            prev1 = cur;
        }
        return prev1;
    }
}

Verdict: The template for this family.

Before you submit

Edge cases and common mistakes

Test these inputs

  • One house
  • Two equal houses

Mistakes people make

  • Taking all even or all odd indices (fails on [2, 1, 1, 2]).

Interview

Follow-up questions

What if houses form a binary tree (House Robber III)?