Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in Go: Dynamic Programming with Two Totals

Practice O(n) Read the full explanation

You get an array 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

    GO · DYNAMIC PROGRAMMING

    House Robber in Go, explained

    Problem overview

    The function rob receives a slice nums where nums[i] is the money in house i. Two neighbouring houses can't both be robbed, and the task is to return the largest total you can take. There are between 1 and 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. For [2, 1, 1, 2] the answer is 4, by robbing houses 0 and 3. Robbing every other house would give only 3, so skipping two houses in a row can pay off.

    Approach: rob it or skip it

    Decide house by house, 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 its money joins the best total for the houses up to i - 2.

    The better of the two choices is the best total up to house i. That choice is the whole algorithm. Trying every subset of houses would take exponential time, but this rule needs only two earlier results, so two running totals are enough and no table is required.

    The same program, run on [2, 7, 9, 3, 1], prints these values per round:

    i 0 nums[i] 2 prev 0 curr 0 best 2
    i 1 nums[i] 7 prev 0 curr 2 best 7
    i 2 nums[i] 9 prev 2 curr 7 best 11
    i 3 nums[i] 3 prev 7 curr 11 best 11
    i 4 nums[i] 1 prev 11 curr 11 best 12

    At house 3 the money is 3, and robbing it would give 7 + 3 = 10, which is less than the 11 already available, so the total stays at 11.

    Step by step

    1. Create prev as 0. At the start of each round it is the best total for the houses up to two before the current one.
    2. Create curr as 0. It is the best total for 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 over every house with i from 0 while i < len(nums). Each house is decided once.
    4. Compute best as the larger of curr (skip the house) and prev + nums[i] (rob it).
    5. Move both totals one house to the right. Set prev to curr first, then curr to best, so prev gets the old value of curr.
    6. Return curr. After the last house it is the best total for the whole street.

    The solution in Go

    func rob(nums []int) int {
        prev := 0
        curr := 0
        for i := 0; i < len(nums); i++ {
            best := max(curr, prev+nums[i])
            prev = curr
            curr = best
        }
        return curr
    }
    

    The Go details worth a closer look:

    • The built-in max. Since Go 1.21, max and min are built-in functions for numbers and strings, so no import and no hand-written helper is needed. The lessons use Go 1.22.
    • Slices carry their length. len(nums) is the number of houses. An empty or nil slice has length 0, so the loop simply doesn't run.
    • Indexing is checked. nums[i] with i outside the slice stops the program with a run-time panic, so the loop condition i < len(nums) must be strict.
    • best is local to the loop body. It is created with := in every round, while prev and curr keep their values across rounds.

    Complexity

    Time: O(n), where n is the number of houses. Each house is visited once with constant work.

    Space: O(1). Only prev, curr and best, whatever the length of the slice.

    Edge cases and common mistakes

    • Greedy choices. Taking every other house, or always the biggest house, can fail. For [2, 1, 1, 2] every other house gives 3, while the answer is 4.
    • Overwriting in the wrong order. If curr = best is written before prev = curr, then prev receives the new total instead of the old one, and the next round adds to the wrong value.
    • A single house. [5] gives 5: max(0, 0 + 5).
    • Zeros. [0, 0, 0] gives 0. Houses with no money never hurt the totals.
    • Two houses. [3, 10] gives 10, the larger of the two, because they are neighbours.
    • Empty slice. The constraints promise at least one house, but this code would return 0 for an empty slice.

    Testing

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