House Robber - Medium - NL

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/house-robber/

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.

Approach

  • Dp based solution of not picking the adjacent ones.

Solution

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