### leetcode : 198. House Robber

Posted on

This is another dynamic programming problem. The way to solve this is to focus only which is greater A) sum of houses robbed until element i or B) the sum of houses robbed up to i-1

The reason we have to make the this decision comes down to the fact that we cannot rob adjacent houses so we have to calculate weather its more profitable to rob the current house or the adjacent houses.

The defaults are the following

• If there are no houses, return 0
• If there is only 1 house return the value of house 1
• If there are 2 houses, return the grater value of house 1 or house 2

after being aware of the above, lets create an array to hold the return value if n were to have equaled i. To rephrase, break the problem size down. Instead of worrying about what happens when the array size is n, lets worry about what would we return if we stopped the array right now.

``````var rob = function(nums) {
if(!nums || nums.length === 0){return 0}
if(nums.length === 1){return nums}
if(nums.length === 2){return Math.max(nums,nums)}
const arr = new Array(nums.length).fill(0)
arr=nums
arr=Math.max(nums,nums)
for(i=2;i<nums.length;i++){
arr[i] = Math.max(nums[i] + arr[i-2], arr[i-1])
})
return Math.max(arr[arr.length-1],arr[arr.length-2])
};``````

If you are having a problem understanding, just walk through the first few steps

If nums is 4,2,8,9,0 this is what we would fill our new array with

•  -> nums -> 4
•  -> the greater of nums or nums -> 4
•  -> the greater of nums + array = 12 or array = 2 -> 12
•  -> the greater of nums + array = 13 or array = 12 -> 13
•  -> the greater of nums + array = 12 or array = 13 -> 13

We return 13