DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Edited on

House Robber leetcode problem

#dp

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:

Input: nums = [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.
Memoization approach:

class Solution {
    public int rob(int[] nums) {
     int dp[] = new int[nums.length];
        Arrays.fill(dp,-1);
        return max(0,nums,dp);
    }
    public int max(int index, int nums[],int dp[]){
        //base case
        if(index>=nums.length) return 0;
        if(dp[index]!=-1) return dp[index];
        int take = nums[index] + max(index+2,nums,dp);
        int dontTake = 0 + max(index+1,nums,dp);

        return dp[index] = Integer.max(take,dontTake);
    }
}
Enter fullscreen mode Exit fullscreen mode

Tabulation approach:

class Solution {
    public int rob(int[] nums) {
        //we can solve it using tabulation dp with memory optimization
        //tabulation is bottom up approach 
        int prev  = nums[0];
        int prevOfPrev = 0;// initialy
        for(int i =1;i<nums.length;i++){
            int take = nums[i];
            if(i>1) take+=prevOfPrev;
            int dontTake = 0 + prev;
            int currentVal = Integer.max(take,dontTake);
            prevOfPrev = prev;
            prev = currentVal;
        }
        return prev;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)