← Back to Algorithms, page 4

algorithms-0079 · Medium fresher

House robber: choose houses along a street to maximise the total money taken when two neighbouring houses cannot both be chosen, then solve it for houses arranged in a circle.

For each house decide to take it (add its value to the best answer two houses back) or skip it (keep the best answer one house back): best(i) = max(best(i-1), best(i-2) + nums[i]). Two running variables give O(n) time and O(1) space. In a circle the first and last houses are adjacent, so solve the line twice, once without the first house and once without the last, and take the larger.

Full answer

Problem

Given non-negative values nums for houses in a row, return the largest sum of values you can take without taking two adjacent houses. Then solve it when the houses form a circle.

Example: [2, 7, 9, 3, 1] gives 12 (2 + 9 + 1). In a circle, [2, 3, 2] gives 3, because the two 2s are neighbours.

Constraints: 1 <= n <= 100 (larger is fine), values from 0 to 400.

Brute force

Try every subset with no two adjacent houses: there are Fibonacci(n) such subsets, so the cost grows exponentially (about 1.6^n).

Optimal approach

Keep prev2 (best up to house i - 2) and prev1 (best up to house i - 1). For each value x: prev2, prev1 = prev1, max(prev1, prev2 + x). The answer is prev1.

Circle: if there is one house, return its value. Otherwise return max(rob(nums[1:]), rob(nums[:-1])).

Why it works

Consider the best plan for the first i houses. Either it skips house i, in which case it is the best plan for the first i - 1 houses, or it takes house i, in which case house i - 1 is excluded and the rest is the best plan for the first i - 2. Taking the max of the two covers every option. For the circle, any valid plan leaves out the first house or the last house (or both), so one of the two line problems contains it.

Complexity

O(n) time and O(1) space; the circle version runs the line version twice.

Code

python
import random
from itertools import product


def rob(nums):
    """Max sum with no two adjacent houses. best(i) = max(best(i-1), best(i-2) + nums[i]). O(n), O(1)."""
    prev2, prev1 = 0, 0                  # best up to i-2, best up to i-1
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1


def rob_circle(nums):
    """Houses in a circle: first and last are adjacent. Solve twice, skipping one end each time."""
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[1:]), rob(nums[:-1]))


def brute(nums, circle=False):
    best = 0
    n = len(nums)
    for pick in product((0, 1), repeat=n):
        if any(pick[i] and pick[i + 1] for i in range(n - 1)):
            continue
        if circle and n > 1 and pick[0] and pick[-1]:
            continue
        best = max(best, sum(x for x, p in zip(nums, pick) if p))
    return best


if __name__ == "__main__":
    assert rob([1, 2, 3, 1]) == 4
    assert rob([2, 7, 9, 3, 1]) == 12
    assert rob([]) == 0 and rob([5]) == 5
    assert rob_circle([2, 3, 2]) == 3 and rob_circle([1, 2, 3, 1]) == 4
    rng = random.Random(79)
    for _ in range(1000):
        a = [rng.randint(0, 20) for _ in range(rng.randint(1, 10))]
        assert rob(a) == brute(a)
        assert rob_circle(a) == brute(a, circle=True)
    print("all tests passed")

Save as b79_house_robber.py and run python3 b79_house_robber.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list (0). One house (its value). Two houses (the larger). All zeros. The circular single-house case must not slice away the only house.

Pattern

Take-or-skip DP over a sequence with a "no two adjacent" constraint. Related: delete and earn (reduce to house robber over values), maximum sum of non-adjacent elements, the tree version (return a pair "with root" and "without root" per node), and paint fence problems.

python
import random
from itertools import product


def rob(nums):
    """Max sum with no two adjacent houses. best(i) = max(best(i-1), best(i-2) + nums[i]). O(n), O(1)."""
    prev2, prev1 = 0, 0                  # best up to i-2, best up to i-1
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1


def rob_circle(nums):
    """Houses in a circle: first and last are adjacent. Solve twice, skipping one end each time."""
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[1:]), rob(nums[:-1]))


def brute(nums, circle=False):
    best = 0
    n = len(nums)
    for pick in product((0, 1), repeat=n):
        if any(pick[i] and pick[i + 1] for i in range(n - 1)):
            continue
        if circle and n > 1 and pick[0] and pick[-1]:
            continue
        best = max(best, sum(x for x, p in zip(nums, pick) if p))
    return best


if __name__ == "__main__":
    assert rob([1, 2, 3, 1]) == 4
    assert rob([2, 7, 9, 3, 1]) == 12
    assert rob([]) == 0 and rob([5]) == 5
    assert rob_circle([2, 3, 2]) == 3 and rob_circle([1, 2, 3, 1]) == 4
    rng = random.Random(79)
    for _ in range(1000):
        a = [rng.randint(0, 20) for _ in range(rng.randint(1, 10))]
        assert rob(a) == brute(a)
        assert rob_circle(a) == brute(a, circle=True)
    print("all tests passed")

Rolling two-variable DP for a line and the two-run reduction for a circle, checked against all subsets on random inputs.

Complexity

Time: O(n). Space: O(1). The circular version is two linear passes over slices; index bounds avoid copying if needed.

By level

Fresher: Writes the take-or-skip recurrence and traces it on a short list. Explains why picking every other house is not always best.

Mid: Solves the circle version with two passes and reconstructs the chosen houses. Extends the idea to the tree version with paired values.

Senior: Generalizes to constraint-separated selections such as k-gap rules and weighted interval scheduling. Discusses how the recurrence maps to a small state machine, which helps derive similar DPs quickly.

Key points

  • best(i) = max(skip, take)
  • Take means adding to best(i - 2)
  • Two variables are enough
  • Circle: drop the first or drop the last
  • Handle n = 1 separately in the circle

Common mistakes

  • Greedy choice of the largest values
  • Alternating even and odd indices only
  • Forgetting the n = 1 case in the circle
  • Off-by-one in the rolling update

Follow-ups

  • How would you solve it on a binary tree?
  • How would you return which houses were chosen?
  • How does delete and earn reduce to this?

Tips

  • State the take-or-skip choice in one sentence
  • Explain the circle reduction
  • Show a counterexample to the even/odd idea

Evaluation rubric

  • Correct recurrence
  • O(1) space
  • Correct circle handling
  • Edge cases