House Robber

House Robber

House Robber - 1D Dynamic Programming

My approach:

If you observe closely. It is simply asking us to find the maximum sum of subsequences with the condition that no two elements are adjacent.

So in every condition, if the element is selected then the element next to it won't be in the subsequence.

My solution:

  • Recursive:

image1

  • Iterative:

image2

Code:

  • Recursion with Memoization:

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

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

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

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

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

int maxMoneyLooted(vector<int> &houses, int n)
{
    vector<int> dp(n,-1);
    return helper(houses,n,0,dp);
}
  • Dynamic Programming:

int maxMoneyLooted(vector<int> &houses, int n)
{
    vector<int> dp(n);

    dp[0] = houses[0];
    dp[1] = max(houses[0], houses[1]);

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

        int pick = houses[i]+dp[i-2];
        int notPick = dp[i-1];

        dp[i] = max(pick,notPick);
    }

    return dp[n-1];

}

https://www.codingninjas.com/studio/problems/loot-houses_630510