Algo-Sim › Dynamic Programming

House Robber

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

For each house, either skip it (keep the best so far) or rob it on top of the best from two houses back.

Problem

Houses along a street hold nums[i] money each. Robbing two adjacent houses sets off an alarm. Return the most money you can take without robbing two neighbours.

Constraints

Edge cases to test

Follow-up questions

What if the houses form a circle?
Run the line version twice, without the first and without the last house (LC 213).
What if the houses form a binary tree?
Return (rob this node, skip this node) from each subtree in a post-order DFS (LC 337): O(n).

Solution

Java

public int rob(int[] nums) {
    int[] dp = new int[nums.length + 1];
    dp[1] = nums[0];
    for (int i = 2; i <= nums.length; i++) {
        dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
    }
    return dp[nums.length];
}

Python

def rob(nums):
    dp = [0] * (len(nums) + 1)
    dp[1] = nums[0]
    for i in range(2, len(nums) + 1):
        dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])
    return dp[len(nums)]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int rob(vector<int> &nums) {
        vector<int> dp = vector<int>(int(nums.size()) + 1);
        dp[1] = nums[0];
        for (int i = 2; i <= int(nums.size()); i++) {
            dp[i] = std::max(dp[i - 1], dp[i - 2] + nums[i - 1]);
        }
        return dp[int(nums.size())];
    }
};

More Dynamic Programming problems