Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in Kotlin: 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

    KOTLIN · DYNAMIC PROGRAMMING

    House Robber in Kotlin, explained

    Problem overview

    The function rob receives an IntArray named nums, where nums[i] is the money in house i. Two neighbouring houses can't both be robbed, and the function returns the largest total you can take. The constraints are 1 to 100 houses with 0 to 400 in each.

    For [2, 7, 9, 3, 1] the answer is 12, from houses 0, 2 and 4 (2 + 9 + 1). For [2, 1, 1, 2] the answer is 4, from the two ends. Robbing every other house gives only 3 here, whichever end you start from, so a fixed pattern of skipping exactly one house isn't enough. Sometimes the best plan skips two in a row.

    Approach: decide house by house

    Walk the street from left to right and keep the best total for the houses seen so far. At house i there are two choices:

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

    The better of the two is the best total up to house i. Each answer depends only on the previous two, so two running totals are enough: curr for the houses before the current one, and prev for the houses before that. Reusing earlier answers instead of trying every combination of houses is dynamic programming. Trying every subset of non-adjacent houses would take exponential time, while this takes one pass.

    Here is the loop for [2, 7, 9, 3, 1], printing the values at each house:

    i=0 house=2 prev=0 curr=0 best=2
    i=1 house=7 prev=0 curr=2 best=7
    i=2 house=9 prev=2 curr=7 best=11
    i=3 house=3 prev=7 curr=11 best=11
    i=4 house=1 prev=11 curr=11 best=12
    end 12
    

    At house 3 the best stays 11: robbing it would give 7 + 3 = 10, which is worse than skipping it. At house 4 the choice 11 + 1 = 12 wins.

    Step by step

    1. Create prev as a var equal to 0. Before the first house nothing has been robbed.
    2. Create curr as a var equal to 0 for the same reason.
    3. Loop i over 0 until nums.size. Every house is decided exactly once.
    4. Compute best as maxOf(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. The opposite order would lose the old curr.
    6. Return curr. After the last house it is the best total for the whole street.

    The solution in Kotlin

    class Solution {
    
        fun rob(nums: IntArray): Int {
            var prev = 0
            var curr = 0
            for (i in 0 until nums.size) {
                val best = maxOf(curr, prev + nums[i])
                prev = curr
                curr = best
            }
            return curr
        }
    }
    

    The Kotlin details worth a look:

    • 0 until nums.size is a range that excludes its upper end, so i takes the values 0 to nums.size - 1, the valid indices of an IntArray. Writing 0..nums.size would include nums.size and throw an ArrayIndexOutOfBoundsException on the last round. Kotlin also offers nums.indices for the same range.
    • maxOf is a standard-library function that returns the larger of its arguments, so no import is needed.
    • IntArray is a fixed-size array of primitive int values on the JVM. It has size as a property, not a length() method, and it is indexed with nums[i].
    • var versus val. prev and curr change in every round, so they are var. best is assigned once per round, so it is a val declared inside the loop.
    • Int overflow. The totals are at most 100 × 400 = 40,000, far below the 32-bit limit, so overflow isn't a concern here.

    Complexity

    Time: O(n), where n is the number of houses. The loop makes one pass with a constant amount of work per house.

    Space: O(1). The function stores two totals, one temporary and the loop counter. A version with a table of best totals per house would use O(n).

    Edge cases and common mistakes

    • One house. For [5] the loop runs once with prev = 0 and curr = 0, so best is 5 and the function returns 5.
    • Two houses. For [3, 10] the answer is 10. You can only take one of the two, and the larger wins.
    • All zeros. [0, 0, 0] returns 0.
    • Taking every other house. This fails on [2, 1, 1, 2], where both parities give 3 but the answer is 4. In [400, 1, 1, 400, 1] the answer is 800, from houses 0 and 3, which isn't a strict every-other pattern either.
    • Adding to curr instead of prev. The expression curr + nums[i] robs the house next to the last robbed one. On [1, 2, 3, 1] that sums every house and returns 7 instead of 4.
    • Wrong update order. Setting curr = best before prev = curr makes prev equal to best and drops the older total.

    Testing

    These inputs give the following results from 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, 10] gives 10.
    • [0, 0, 0] gives 0.
    • [400, 1, 1, 400, 1] gives 800.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free