Dynamic Programming · Pattern 2 of 12

Pick or not pick: House Robber

At each item you either take it (and must skip its neighbour) or leave it. best(i) = max(best(i - 1), best(i - 2) + nums[i]), and two variables are enough.

2 variations · 2 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Choose items with no two adjacent ones
  • Each item is either taken or skipped, and taking it blocks a neighbour
  • Items arranged in a circle, so first and last are neighbours

The template

Alternate Selection / Pick / Not pick
// best(i) = max(skip house i: best(i - 1), rob it: best(i - 2) + nums[i])
int robRange(int[] nums, int lo, int hi) {
    int prev2 = 0, prev1 = 0;              // best up to i - 2, best up to i - 1
    for (int i = lo; i <= hi; i++) {
        int cur = Math.max(prev1, prev2 + nums[i]);
        prev2 = prev1;
        prev1 = cur;
    }
    return prev1;
}

int rob(int[] nums) {
    return robRange(nums, 0, nums.length - 1);
}

// houses in a circle: the first and last cannot both be robbed, so drop one of them
int robCircle(int[] nums) {
    int n = nums.length;
    if (n == 1) return nums[0];
    return Math.max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1));
}

The variations

  1. 1A line of items

    Two choices per house. Skip it and keep the best so far, or rob it and add it to the best from two houses back. The answer only ever looks two steps back.

  2. 2A circle of items

    The first and last houses are neighbours, so at least one of them is skipped. Solve the line twice, once without the first house and once without the last, and take the better.

Mistakes to avoid

  • Greedily taking every other house: [2, 1, 1, 2] is best as 2 + 2, which skips two in a row.
  • House Robber II with one house: both ranges are empty, so return nums[0] first.
Next: 2D DP: grids and two-index states →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.