DEV Community 👩‍💻👨‍💻

Prashant Mishra
Prashant Mishra

Posted 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.

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)

Super Useful CSS Resources

>> Check out this classic DEV post <<