Start learning free

LESSON 522 OF 671 · DYNAMIC PROGRAMMING

House Robber in Java: O(n) Dynamic Programming

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

    JAVA · DYNAMIC PROGRAMMING

    House Robber in Java, explained

    Problem overview

    The method rob receives an int[] named nums, where nums[i] is the money in house i. Two neighboring houses can't both be robbed, and the method returns the largest total you can collect. The constraints are 1 to 100 houses, each holding 0 to 400.

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

    Approach: skip or rob, house by house

    Trying every allowed subset of houses is far too slow, since the number of subsets doubles with every house. Two natural shortcuts are wrong as well. Robbing every other house fails for [2, 1, 1, 2]: both the even and the odd houses total 3, but robbing houses 0 and 3 gives 4. Greedily grabbing the richest house fails too, since it can block two neighbors that are worth more together.

    The way out is to decide one house at a time, using only the best totals for the houses before it. For house i there are two choices:

    • Skip it. The best total is the best for the houses before it, which we call curr.
    • Rob it. Then house i - 1 must stay untouched, so its money adds to the best total from the houses up to i - 2, which we call prev.

    The better of the two, Math.max(curr, prev + nums[i]), is the best total up to house i. That is the whole algorithm, and each answer reuses two earlier ones, which makes it dynamic programming. Only two earlier answers are ever needed, so two variables replace a table.

    Here is the run for [2, 7, 9, 3, 1], showing the values at the start of each round:

    inums[i]prevcurrbest
    02002
    17027
    292711
    3371111
    41111112

    At i = 3 skipping wins: robbing the 3 would give 7 + 3 = 10, less than the 11 already available. The method returns 12.

    Step by step

    1. Create prev = 0. It is the best total for the houses up to two before the current one. Before the first house nothing has been robbed.
    2. Create curr = 0. It is the best total for the houses up to the one just before the current one.
    3. Loop over every index from 0 while i < nums.length. Each house is decided exactly once.
    4. Compute best as the larger of skipping (curr) and robbing (prev + nums[i]), using Math.max.
    5. Move both totals one house to the right: prev = curr first, then curr = best. The reverse order would overwrite the value prev needs.
    6. Return curr. After the last house it is the best total for the whole street.

    The solution in Java

    class Solution {
        public int rob(int[] nums) {
            int prev = 0;
            int curr = 0;
            for (int i = 0; i < nums.length; i++) {
                int best = Math.max(curr, prev + nums[i]);
                prev = curr;
                curr = best;
            }
            return curr;
        }
    }
    

    Java details worth noticing:

    • Math.max on ints. It takes two values and returns the larger, with no need for an if.
    • Arrays know their length. nums.length is a field, with no parentheses, unlike String.length().
    • best is local to the loop body. A new variable is declared every round, which is fine for a primitive.
    • No overflow worries here. At most 100 houses of at most 400 each add up to 40,000, far below the int limit of 2,147,483,647.

    Complexity

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

    Space: O(1): three integers, whatever the size of the input. The input array itself is only read, never changed.

    Edge cases and common mistakes

    • A single house. For [5] the loop runs once: best = max(0, 0 + 5) = 5, and the method returns 5.
    • Two houses. For [3, 10] the answer is 10, the larger of the two, because they are neighbors. The method gives 10.
    • All zeros. [0, 0, 0] returns 0. Zero is a legal amount, and the totals simply stay at 0.
    • Assuming alternate houses. Skipping two houses in a row can pay off. For [1, 3, 1, 3, 100] the best total is 103, from houses 1 and 4, while houses 0, 2 and 4 give only 102.
    • Updating in the wrong order. curr = best; prev = curr; makes both variables equal, and every later round then adds nums[i] to the wrong total.

    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.
    • [0, 0, 0] gives 0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free