House Robber II

House Robber II

House Robber II - 1D Dynamic Programming

Note:

It is highly recommended that you first attempt House Robber to get a good understanding of this question.

My approach:

As I mentioned to solve House Robber problem before attempting this problem.

At first look, this question might sound tricky but is it actually that tricky?

If you look closely only one condition is added that they are in a circular arrangement. That means if I include the 1st house then I can't include the last house and if I include the last house I have to exclude 1st house.

So in both cases, the original size of the array changes with the change in the starting index.

My solution:

  • Recursive:

image1

  • Iterative:

image2

Code:

  • Recursion with Memoization:

    Time Complexity : O(n)

    Space Complexity : O(n)

long long int helper(vector<int>& valueInHouse,int n,int s,vector<long long int>& dp){

    if(s>=n){
        return 0;
    }

    if(dp[s]!=-1){
        return dp[s];
    }

    long long int pick = valueInHouse[s]+helper(valueInHouse,n,s+2,dp);
    long long int notPick = helper(valueInHouse,n,s+1,dp);

    dp[s] = max(pick,notPick);

    return max(pick,notPick);
}   

long long int houseRobber(vector<int>& valueInHouse)
{
    // Write your code here.
    int n = valueInHouse.size();
    if(n==1){
        return valueInHouse[0];
    }

    vector<long long int> dp1(n-1,-1);
    vector<long long int> dp2(n,-1);

    long long int pickFirst = helper(valueInHouse,n-1,0,dp1);
    long long int notPickFirst = helper(valueInHouse,n,1,dp2);

    return max(pickFirst,notPickFirst);
}
  • Dynamic Programming

    Time Complexity : O(n)

    Space Complexity : O(n)


long long int houseRobber(vector<int>& valueInHouse)
{
    // Write your code here.
    int n = valueInHouse.size();

    if(n==1){
        return valueInHouse[0];
    }

    vector<long long int> dp1(n-1);
    vector<long long int> dp2(n-1);

    dp1[0] = valueInHouse[0];
    dp1[1] = max(valueInHouse[0], valueInHouse[1]);

    dp2[0] = valueInHouse[1];
    dp2[1] = max(valueInHouse[1], valueInHouse[2]);

    for(int i=2;i<n-1;i++){

        dp1[i] = max(dp1[i-1],valueInHouse[i]+dp1[i-2]);
        dp2[i] = max(dp2[i-1], valueInHouse[i+1]+dp2[i-2]);

    }
    return max(dp1[n-2],dp2[n-2]);
}

https://www.codingninjas.com/studio/problems/house-robber_839733?leftPanelTab=1