Start learning free

LESSON 240 OF 321 · DYNAMIC PROGRAMMING

House Robber in Python: Dynamic Programming with Two Variables

Practice O(n) Read the full explanation

You get a list nums, the money in each house along a street. House i holds nums[i].

Return the most money you can rob.

Houses next to each other share an alarm. So you can never rob two neighbors.

Example 1:

Input: nums = [3, 10, 3, 1, 2]
Output: 12
Explanation: The best pick is house 1 (10) and house 4 (2).
That gives 10 + 2 = 12.
Robbing houses 0, 2 and 4 gives only 3 + 3 + 2 = 8.

Example 2:

Input: nums = [6, 1, 2, 7]
Output: 13
Explanation: Rob house 0 (6) and house 3 (7).
That gives 6 + 7 = 13.
Houses 1 and 2 are both skipped, and that is allowed.

Example 3:

Input: nums = [9]
Output: 9
Explanation: With one house, rob it.

Constraints:

  • 1 to 100 houses.
  • Each house holds from 0 to 400.

STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    House Robber in Python, explained

    Problem overview

    The method rob receives a list nums where nums[i] is the money in house i. Robbing two neighbouring houses sets off an alarm, so no two chosen houses may be adjacent. The method returns the largest total you can take. The list has 1 to 100 houses, each holding 0 to 400.

    For [2, 7, 9, 3, 1] the answer is 12: houses 0, 2 and 4 give 2 + 9 + 1.

    Approach: decide house by house

    Choosing every other house isn't always best. In [2, 1, 1, 2] the best total is 4, from the first and last houses, while alternating houses gives only 3. A fixed pattern fails, so the algorithm has to compare options.

    Walk through the houses from left to right. At house i there are two choices:

    • Skip it. The best total is whatever was best for the houses before it.
    • Rob it. Then house i - 1 must stay untouched, so the money adds to the best total for the houses before i - 1.

    The larger of the two is the best total up to house i. Each decision needs only two earlier results, so two running totals are enough.

    Step by step

    1. Create prev = 0: the best total from the houses up to two houses before the current one.
    2. Create curr = 0: the best total from the houses up to the one just before the current one. Before the first house nothing has been robbed, so both start at 0.
    3. Loop i over range(len(nums)). Every house is decided once, using only totals for the houses before it.
    4. Compute best as max(curr, prev + nums[i]): skip the house, or rob it.
    5. Move both totals one house to the right: prev takes curr, then curr takes best. Reversing the order would overwrite the value prev needs.
    6. Return curr, the best total for the whole street.

    The solution in Python

    class Solution:
        def rob(self, nums: List[int]) -> int:
            prev = 0
            curr = 0
            for i in range(len(nums)):
                best = max(curr, prev + nums[i])
                prev = curr
                curr = best
            return curr
    

    Tracing nums = [2, 7, 9, 3, 1] gives these values at the end of each round:

    inums[i]prevcurr
    0202
    1727
    29711
    331111
    411112

    At i = 3 robbing the house would give 7 + 3 = 10, less than the 11 already available, so the house is skipped and curr stays at 11.

    Python details worth knowing: max takes any number of values and returns the largest. range(len(nums)) gives the indices 0 to len(nums) - 1. The type hint List[int] only documents the parameter and doesn't convert anything.

    Complexity

    Time: O(n) for n houses: one pass with constant work per house. Space: O(1), because only two totals and a few temporaries are kept.

    Edge cases and common mistakes

    • One house. [5] returns 5: max(0, 0 + 5).
    • Two houses. [3, 1] returns 3, the larger one, because they are neighbours.
    • Zeros. [0, 0] returns 0.
    • Alternating houses. [2, 1, 1, 2] returns 4, so a rule such as "take the even positions or the odd ones" is wrong.
    • A big house late in the list. [1, 3, 1, 3, 100] returns 103: the 100 is added to the best total from before its neighbour.
    • Adding to curr instead of prev. curr + nums[i] would rob two neighbours.

    Testing

    • [1, 2, 3, 1] gives 4.
    • [2, 7, 9, 3, 1] gives 12.
    • [2, 1, 1, 2] gives 4.
    • [5] gives 5.
    • [3, 1] gives 3.
    • [1, 3, 1, 3, 100] gives 103.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free