15% off all plans & roadmaps Use code

See plans

House Robber

Updated

TL;DR: Pick houses along a street so that no two chosen houses are neighbors, and maximize the total money. At each house you either skip it or rob it plus the best total from two houses back, which needs only two running variables.

Problem

You are a professional robber planning to rob houses along a street. Each house holds some money. Adjacent houses share a security system, and it contacts the police if two adjacent houses are broken into on the same night.

Given an integer array nums where nums[i] is the money in house i, return the maximum amount you can rob tonight without alerting the police.

Example 1

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1), then rob house 3 (money = 3). The total is 1 + 3 = 4.

Example 2

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), house 3 (money = 9) and house 5 (money = 1). The total is 2 + 9 + 1 = 12.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Constraints that matter

  • nums.length is at most 100, but a two-way recursion that branches at every house makes about 2^n calls in the worst case. Brute force is therefore far too slow even for this small n.
  • Every nums[i] is at least 0, so skipping a house never helps you by itself. You never need to worry about negative values or about forcing a pick.
  • The largest possible total is 100 * 400 = 40,000 at most, which fits in a 32-bit integer in every language. You do not need long or big integers.
  • nums.length is at least 1, so there is always a first house. You still want a recurrence that works with zero houses, because it removes special cases.
  • Only the two previous answers feed the next one, so O(1) extra space is possible.

View on LeetCode

Hints

Hint 1

This is dynamic programming on a line.

Hint 2

Try every legal choice.

Solution

Intuition

This is dynamic programming on a line. Look at the last house. Either you rob it or you do not, and each choice leaves a smaller version of the same problem.

Picture two sticky notes stacked on a desk, with the top note holding prev1 and the note beneath it holding prev2. Each house writes a new top note with the larger option, the old top slides down, and the bottom note falls off.

If you rob house i, house i - 1 is off limits. Your total is nums[i] plus the best you can do on houses 0..i-2. If you skip house i, your total is the best you can do on houses 0..i-1. The answer for the first i + 1 houses is the larger of those two numbers.

The best total for a prefix does not depend on which houses produced it. Only the number matters. So each prefix answer needs only two earlier answers, and the same prefix answers get reused many times. That repeated work makes plain recursion exponential, and a table or two variables removes it.

The recurrence has the same shape as Fibonacci, with max in place of +. Write best[i] = max(best[i-1], best[i-2] + nums[i]) and treat the best of an empty prefix as 0. Then no base-case branching is needed.

Watch the pattern animation

Worked example

Input: nums = [6, 7, 1, 30, 8, 2, 4]
Output: 41
Explanation: Rob the houses holding 7, 30 and 4. They sit at indices 1, 3 and 6, so no two are adjacent, and 7 + 30 + 4 = 41. Taking 6, 1, 8 and 4 gives only 19, and taking 6, 30 and 4 gives 40, so 41 is the best.

Approach 1: Brute force recursion

Try every legal choice. For house i, you either rob it and move on to house i - 2, or skip it and move on to house i - 1. Take the larger result. When the index drops below 0, there are no houses left and the result is 0.

These two options cover every legal plan for the first i + 1 houses, so the answer is correct. It is slow because nothing is remembered.

Steps

  1. Define best(i) as the most money you can rob from houses 0..i.
  2. If i < 0, return 0.
  3. Compute skip = best(i - 1).
  4. Compute take = nums[i] + best(i - 2).
  5. Return the larger of skip and take.
  6. Call best(n - 1) and return that value.

Dry run

Run on [6, 7, 1, 30, 8, 2, 4]. The call best(6) becomes max(best(5), 4 + best(4)).

The call best(5) becomes max(best(4), 2 + best(3)), so best(4) is already evaluated twice. Each of those calls best(3), so best(3) runs three times in total, and the repeats keep multiplying toward the leaves.

When the tree finally bottoms out, the values are best(5) = 39 and best(4) = 37. Then best(6) = max(39, 4 + 37) = 41. Counting every call including the ones that return 0 at a negative index, this tiny input already makes 67 calls.

Complexity

TimeO(2^n)
SpaceO(n)

Here n is the number of houses. Each call with index i makes two calls, one with i - 1 and one with i - 2, so the call count follows T(i) = 1 + T(i-1) + T(i-2). That grows like Fibonacci numbers, which is exponential in n, roughly 1.6^n and bounded by 2^n. The recursion depth is at most n, so the call stack uses O(n) space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rob(self, nums: List[int]) -> int:
        def best(i: int) -> int:
            # No houses left to consider
            if i < 0:
                return 0
            skip = best(i - 1)
            take = nums[i] + best(i - 2)
            return max(skip, take)

        return best(len(nums) - 1)

Approach 2: Memoized recursion

What's slow: best(i) is recomputed every time some larger call needs it. In the trace above, best(3) ran three times, and the repeats grow with every extra house.

The insight that fixes it: best(i) depends only on i, never on how you got there. Compute each index once, store it in an array, and return the stored value on every later visit. There are only n distinct indices, so there are only n real computations.

Steps

  1. Create a memo array of size n filled with -1, meaning not computed yet.
  2. In best(i), return 0 when i < 0.
  3. If memo[i] is not -1, return it.
  4. Compute max(best(i - 1), nums[i] + best(i - 2)).
  5. Store that value in memo[i] and return it.
  6. Return best(n - 1).

Dry run

Run on [6, 7, 1, 30, 8, 2, 4]. The first call best(6) calls best(5), which calls down the chain to best(0).

best(0) stores memo[0] = 6. Then best(1) = max(6, 7) = 7, best(2) = max(7, 6 + 1) = 7, best(3) = max(7, 7 + 30) = 37, best(4) = max(37, 7 + 8) = 37, and best(5) = max(37, 37 + 2) = 39.

Back at best(6), the second branch needs best(4). That is a memo hit, so it returns 37 at once. The result is max(39, 4 + 37) = 41.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of houses. Each index is computed once, because afterwards its memo entry is filled, and each computation does O(1) work plus two lookups. That is at most 2n + 1 calls in total. The memo array holds n integers and the recursion goes n levels deep, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rob(self, nums: List[int]) -> int:
        memo = [-1] * len(nums)

        def best(i: int) -> int:
            if i < 0:
                return 0
            if memo[i] != -1:
                return memo[i]
            # Skip house i, or rob it and jump back two houses
            memo[i] = max(best(i - 1), nums[i] + best(i - 2))
            return memo[i]

        return best(len(nums) - 1)
1D Array (Fibonacci Style) pattern infographic for House Robber

Solution pattern

1D Array (Fibonacci Style)

Part of Dynamic Programming (DP) Patterns

Approach 3: Bottom-up DP with two variablesOptimal1D Array (Fibonacci Style)

What's slow: memoization is linear in time, but it still stores n values and recurses n levels deep. Every stored value except the last two is never read again.

The insight that fixes it: walk the houses left to right and keep only prev1, the best total up to the previous house, and prev2, the best total up to the house before that. Both start at 0, which stands for an empty prefix. At each house compute max(prev1, prev2 + num), then shift the two variables forward. No base cases and no array are needed.

Steps

  1. Set prev2 = 0 and prev1 = 0.
  2. For each num in nums, compute cur = max(prev1, prev2 + num).
  3. Set prev2 = prev1.
  4. Set prev1 = cur.
  5. After the loop, return prev1.

Dry run

Run on [6, 7, 1, 30, 8, 2, 4]. Both variables start at 0. The table shows the state before each step and the result.

inumprev2prev1prev2 + numcur = max(prev1, prev2 + num)state after (prev2, prev1)
060066(0, 6)
170677(6, 7)
216777(7, 7)
330773737(7, 37)
487371537(37, 37)
5237373939(37, 39)
6437394141(39, 41)

The loop ends with prev1 = 41, which matches the expected output. Rows 2 and 4 show a skip: robbing the house would not beat the running best.

Complexity

TimeO(n)
SpaceO(1)

Here n is the number of houses. The loop runs exactly n times and each pass does one addition, one comparison and two assignments, so time is O(n). The only state is the two integers prev1 and prev2 plus the loop variable, which does not grow with n, so space is O(1). Correctness follows by induction: after step i, prev1 is the best total for houses 0..i and prev2 is the best for 0..i-1.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rob(self, nums: List[int]) -> int:
        prev2 = 0  # best total up to two houses back
        prev1 = 0  # best total up to the previous house
        for num in nums:
            # Skip this house, or rob it on top of prev2
            cur = max(prev1, prev2 + num)
            prev2 = prev1
            prev1 = cur
        return prev1

Common mistakes

  • Returning the larger of the even-index sum and the odd-index sum. On [100, 1, 1, 100] both sums are 101, but robbing indices 0 and 3 gives 200. Use the recurrence, which allows a gap of more than one house.
  • Writing nums[i] + best(i - 1) in the rob branch. Adjacent houses cannot both be robbed, so the rob branch must jump to i - 2.
  • Reading dp[i - 2] in an array version without handling i < 2. That is an out-of-bounds read. Either guard the first two indices, pad with a leading 0, or use two variables that start at 0.
  • Updating prev1 before copying it into prev2. After prev1 = cur, the old value is lost and prev2 ends up equal to prev1. Save cur first, assign prev2 = prev1, then assign prev1 = cur.
  • Returning prev2 instead of prev1 at the end. After the last shift, prev1 holds the answer for the whole array and prev2 holds the answer without the last house.
  • Submitting the plain two-branch recursion. It is correct but makes about 1.6^n calls, so it times out when n is near 100. Add a memo or switch to the loop.

Edge cases

  • [5]: one house. The loop runs once, max(0, 0 + 5) = 5, so the answer is 5.
  • [2, 1]: two houses. You can take only one, so the answer is max(2, 1) = 2.
  • [0, 0, 0]: all zeros. The answer is 0, and the code must not return a negative or an uninitialized value.
  • [100, 1, 1, 100]: the best plan skips two houses in the middle. The answer is 200, and alternating-index sums fail here.
  • [400] * 100: maximum size and value. Robbing every other house gives 50 * 400 = 20000, well inside the int range.
  • [1, 2, 3, 1]: the first sample. The answer is 4, from houses at indices 0 and 2.

Follow-ups interviewers ask

What if the houses form a circle, so the first and last are adjacent?
This is House Robber II. The first and last houses cannot both be robbed, so run the same loop twice. Run it once on nums[0..n-2] and once on nums[1..n-1], and return the larger result. Handle n = 1 separately by returning nums[0].
Can you return which houses to rob, not only the total?
Keep a full table dp of prefix answers instead of two variables. Then walk backward from the end. At index i, if dp[i] == dp[i-1] you skipped the house, so move to i - 1. Otherwise you robbed it, so record i and move to i - 2. That costs O(n) space.
What if the houses form a binary tree and you cannot rob a parent and its child?
This is House Robber III. Run a DFS that returns two numbers per node: the best total if you rob that node, and the best if you skip it. Robbing a node adds its value to the skip values of its children. Skipping it takes the larger of the two values from each child. Each node is visited once, so time is O(n).

House Robber FAQ

What is the time complexity of House Robber?

The optimal solution is O(n) time, where n is the number of houses, because it makes one pass with constant work per house. Plain recursion is O(2^n), and memoized recursion is O(n).

Why use dynamic programming for House Robber?

The best total for a prefix of houses is reused by every longer prefix, and it depends only on the two prefix answers before it. Dynamic programming computes each prefix answer once instead of re-solving it exponentially many times.

Can House Robber be solved in O(1) extra space?

Yes. The recurrence only reads the previous two answers, so two integer variables replace the whole table. You lose the ability to rebuild which houses were robbed, unless you store the full table.

Why is greedy wrong for House Robber?

Taking the largest house first, or taking every other house, can block a better pair. On [2, 7, 9, 3, 1], greedy takes 9 and then 2 and 1, getting 12 by luck. On [2, 10, 3, 3, 10], greedy takes 10 first, then 3, giving 13, while 10 + 10 = 20 is better.

Is the House Robber DP the same as Climbing Stairs?

The recurrence has the same shape, since each state depends on the previous two. Climbing Stairs adds the two values to count ways, while House Robber takes a maximum and adds the current house's money to the value two steps back.

Why initialize prev1 and prev2 to 0 in House Robber?

Zero stands for the best total of an empty set of houses. With both variables at 0, the first house gives max(0, 0 + nums[0]) = nums[0] with no special case, which also covers a one-house input.

Asked at

See which companies ask this — Pro

Practise it