House Robber

Difficulty: Medium

You're robbing houses along a street. nums holds the cash in each house. Robbing two adjacent houses sets off the alarm. Find the most money you can steal without robbing two adjacent houses.

Examples

Input: nums = [1, 2, 3, 1]
Output: 4

Rob house 0 (1) and house 2 (3): 1 + 3 = 4.

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

Rob houses 0, 2, and 4: 2 + 9 + 1 = 12.

Constraints

  • 1 <= nums.length <= 100

  • 0 <= nums[i] <= 400

Approach

At each house, you either rob it or don't. If you skip house i, your best total is the best from the first i houses. If you rob it, you collect nums[i] but can't have robbed house i-1, so add it to the best from the first i-1 houses. Take whichever gives more.

So the best total through house i is max(best through i-1, best through i-2 + nums[i]). As in Climbing Stairs, each step only needs the previous two results, so one sweep with two running values is enough.

Solutions

Brute Force — Plain Recursion

At each house, recursively try 'skip it' and 'rob it' and take the better result. Correct, but solves overlapping subproblems exponentially many times.

function rob(nums) {
  function best(i) {
    if (i < 0) return 0;
    const skip = best(i - 1);
    const take = best(i - 2) + nums[i];
    return Math.max(skip, take);
  }

  return best(nums.length - 1);
}

Time: O(2^n) · Space: O(n) — recursion depth

Optimal — Bottom-Up with Two Variables

Sweep left to right, tracking the best total with only the last two houses' results instead of a full array.

function rob(nums) {
  let prev2 = 0; // best total through two houses ago
  let prev1 = 0; // best total through the previous house

  for (const money of nums) {
    const current = Math.max(prev1, prev2 + money);
    prev2 = prev1;
    prev1 = current;
  }

  return prev1;
}

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