Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in Swift: Dynamic Programming with Two Running 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

    SWIFT · DYNAMIC PROGRAMMING

    House Robber in Swift, explained

    Problem overview

    The method rob receives an array nums, where nums[i] is the money in house i. Two neighbouring houses share a security system, so robbing both on the same night is not allowed. The method returns the most money you can take without robbing two adjacent houses. The constraints are 1 to 100 houses, each holding 0 to 400.

    For [1, 2, 3, 1] the answer is 4: houses 0 and 2 give 1 + 3. For [2, 7, 9, 3, 1] it is 12 (houses 0, 2 and 4: 2 + 9 + 1). For [2, 1, 1, 2] it is 4, taking the first and last houses. Robbing every other house would give only 3 there, so a fixed pattern isn't enough: the choice depends on the amounts.

    Approach: decide house by house

    Walk along the street from left to right. At house i there are two options:

    • Skip it. The best total is then whatever was best for the houses before it.
    • Rob it. Then house i - 1 must stay untouched, so you add nums[i] to the best total for the houses up to i - 2.

    The better of the two is the best total up to house i. This is dynamic programming: each answer is built from answers for shorter streets, and each of those is computed once.

    The choice at house i only looks at the two previous answers, so two variables are enough instead of an array. curr is the best total for the houses before house i, and prev is the best total for the houses before house i - 1. Both start at 0, because before the first house nothing has been robbed.

    The table below follows [2, 7, 9, 3, 1] and comes from a real run. The columns show the values after each round:

    inums[i]bestprevcurr
    02202
    17727
    2911711
    33111111
    41121112

    At i = 2, prev + nums[i] is 2 + 9 = 11, which beats skipping the house (7). At i = 3, robbing would give 7 + 3 = 10, less than 11, so the house is skipped. The final curr is 12.

    Step by step

    1. Create prev with var, set to 0. It is the best total two houses back from the current one. It is a var because the loop changes it.
    2. Create curr the same way, also 0. It is the best total up to the house just before the current one.
    3. Loop over every house. i goes over the half-open range 0..<nums.count. Write the closing brace right away.
    4. Compute best with let. It is max(curr, prev + nums[i]): skip the house, or rob it on top of prev.
    5. Move both totals one house to the right. Set prev to curr first, then curr to best. In the other order, prev would copy the new value and lose the old one.
    6. Return curr after the loop. It is the best total for the whole street.

    The solution in Swift

    class Solution {
    
        func rob(_ nums: [Int]) -> Int {
            var prev = 0
            var curr = 0
            for i in 0..<nums.count {
                let best = max(curr, prev + nums[i])
                prev = curr
                curr = best
            }
            return curr
        }
    }
    

    The Swift details worth a closer look:

    • 0..<nums.count. The half-open range stops before count, so the last index is count - 1. For an empty array it is the empty range 0..<0, so the loop is skipped and the method returns 0. The constraints promise at least one house, but the code handles an empty street too.
    • max is a global function. max(curr, prev + nums[i]) works on any two values of the same comparable type, here two Ints.
    • let versus var. best is created fresh in every round and never changes, so it is a let. prev and curr are assigned in the loop, so they are vars.
    • Safe indexing. Reading nums[i] outside the array stops the program with a run-time error, but the range guarantees that i is always valid.
    • Overflow traps. Int is 64 bits and overflow crashes instead of wrapping. With at most 100 houses of at most 400, the total is at most 40,000, so it is never close.

    Complexity

    Time: O(n), where n is the number of houses. The loop visits each house once and does constant work.

    Space: O(1). The method stores only prev, curr and best.

    Edge cases and common mistakes

    • One house. [5] returns 5: max(0, 0 + 5).
    • Two houses. [3, 4] returns 4. You can take only one, so the larger.
    • Zeros. [0, 0] returns 0.
    • Greedy by position. Taking every other house fails on [2, 1, 1, 2], where the answer is 4 and robbing houses 0 and 2 gives only 3.
    • Greedy by amount. Taking the biggest house first and then what remains can block better pairs. Comparing the two options at every house avoids this.
    • Using curr + nums[i]. That adds the money of house i to a total that may include house i - 1, which breaks the rule.
    • Wrong update order. Setting curr = best before prev = curr leaves both variables equal.

    Testing

    Results from running the reference solution:

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