House Robber

Monisha Mathew
2 min readMay 14, 2019

--

Question: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

You may view the full question here.

Approach 1: Clearly this is a Dynamic Programming problem. And the first approach that comes to my mind is recursion —

//Approach 1:
//Runtime: Time Limit Exceeded (N/A)
//Memory usage: N/A
class Solution {
public int rob(int[] nums) {
return Math.max(findBest(nums, 0, 0), findBest(nums, 1, 0));
}

private int findBest(int[] nums, int n, int sum) {
if(n<nums.length) {
sum+= nums[n];
return Math.max(findBest(nums, n+2, sum), findBest(nums, n+3, sum));
}
return sum;
}
}

Approach 2: Of course, the next approach would be an iterative one using memoization. This discussion forum has been very helpful.

//Approach 2:
//Runtime: 0ms
//Memory usage: 33.1MB
class Solution {
public int rob(int[] nums) {
int[] sum = new int[nums.length];
if(nums.length>0){
sum[0] = nums[0];
} else {
return 0;
}

if(nums.length>1){
sum[1] = Math.max(sum[0], nums[1]);
}

for(int i = 2; i<nums.length; i++) {
sum[i] = Math.max(sum[i-2] + nums[i], sum[i-1]);
}
return sum[nums.length-1];
}
}

Find more posts here.

Cheers & Chao!

--

--