Friday, December 27, 2024
Google search engine
HomeData Modelling & AIFind maximum possible stolen value from houses

Find maximum possible stolen value from houses

There are N houses built in a line, each of which contains some value in it. A thief is going to steal the maximum value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbors left and right sides. The task is to find what is the maximum stolen value.

Examples: 

Input: hval[] = {6, 7, 1, 3, 8, 2, 4}
Output: 19
Explanation: The thief will steal 6, 1, 8 and 4 from the house.

Input: hval[] = {5, 3, 4, 11, 2}
Output: 16
Explanation: Thief will steal 5 and 11

Naive Approach: Below is the idea to solve the problem:

Given an array, the solution is to find the maximum sum subsequence where no two selected elements are adjacent. So the approach to the problem is a recursive solution. 

So there are two cases:

  1. If an element is selected then the next element cannot be selected.
  2. if an element is not selected then the next element can be selected.

Use recursion to find the result for both cases.

Below is the Implementation of the above approach:

C++




// CPP program to find the maximum stolen value
#include <iostream>
using namespace std;
  
// calculate the maximum stolen value
int maxLoot(int* hval, int n)
{
    // base case
    if (n < 0) {
        return 0;
    }
  
    if (n == 0) {
        return hval[0];
    }
    // if current element is pick then previous cannot be
    // picked
    int pick = hval[n] + maxLoot(hval, n - 2);
    // if current element is not picked then previous
    // element is picked
    int notPick = maxLoot(hval, n - 1);
  
    // return max of picked and not picked
    return max(pick, notPick);
}
  
// Driver to test above code
int main()
{
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(hval) / sizeof(hval[0]);
    cout << "Maximum loot possible : "
         << maxLoot(hval, n - 1);
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to find the maximum stolen value
#include <stdio.h>
  
// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}
  
// calculate the maximum stolen value
int maxLoot(int* hval, int n)
{
    // base case
    if (n < 0)
        return 0;
  
    if (n == 0)
        return hval[0];
    // if current element is pick then previous cannot be
    // picked
    int pick = hval[n] + maxLoot(hval, n - 2);
    // if current element is not picked then previous
    // element is picked
    int notPick = maxLoot(hval, n - 1);
  
    // return max of picked and not picked
    return max(pick, notPick);
}
  
// Driver to test above code
int main()
{
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(hval) / sizeof(hval[0]);
    printf("Maximum loot possible : %d ",
           maxLoot(hval, n - 1));
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Java




/*package whatever //do not write package name here */
// Java program to find the maximum stolen value
import java.io.*;
  
class GFG 
{
    
  // Function to calculate the maximum stolen value
  static int maxLoot(int hval[], int n)
  {
      
    // base case
    if (n < 0) {
      return 0;
    }
  
    if (n == 0) {
      return hval[0];
    }
      
    // if current element is pick then previous cannot
    // be picked
    int pick = hval[n] + maxLoot(hval, n - 2);
      
    // if current element is not picked then previous
    // element is picked
    int notPick = maxLoot(hval, n - 1);
  
    // return max of picked and not picked
    return Math.max(pick, notPick);
  }
  
  // driver program
  public static void main(String[] args)
  {
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = hval.length;
    System.out.println("Maximum loot possible : "
                       + maxLoot(hval, n-1));
  }
}
  
// This code is contributed by sanskar84.


Python3




# Python3 program to find the maximum stolen value
  
# calculate the maximum stolen value
def maxLoot(hval,n):
  
    # base case
    if (n < 0):
        return 0
  
    if (n == 0):
        return hval[0]
      
    # if current element is pick then previous cannot be
    # picked
    pick = hval[n] + maxLoot(hval, n - 2)
    # if current element is not picked then previous
    # element is picked
    notPick = maxLoot(hval, n - 1)
  
    # return max of picked and not picked
    return max(pick, notPick)
  
# Driver to test above code
hval = [ 6, 7, 1, 3, 8, 2, 4 ]
n = len(hval)
print("Maximum loot possible : ",maxLoot(hval, n - 1));
  
# This code is contributed by shinjanpatra


C#




// C# program to find the maximum stolen value
using System;
  
public class GFG {
  
    // Function to calculate the maximum stolen value
    static int maxLoot(int[] hval, int n)
    {
  
        // base case
        if (n < 0) {
            return 0;
        }
  
        if (n == 0) {
            return hval[0];
        }
  
        // if current element is pick then previous cannot
        // be picked
        int pick = hval[n] + maxLoot(hval, n - 2);
  
        // if current element is not picked then previous
        // element is picked
        int notPick = maxLoot(hval, n - 1);
  
        // return max of picked and not picked
        return Math.Max(pick, notPick);
    }
  
    static public void Main()
    {
  
        // Code
        int[] hval = { 6, 7, 1, 3, 8, 2, 4 };
        int n = hval.Length;
  
        Console.WriteLine("Maximum loot possible : "
                          + maxLoot(hval, n - 1));
    }
}
  
// This code is contributed by lokesmvs21.


Javascript




<script>
  
// JavaScript program to find the maximum stolen value
  
  
// calculate the maximum stolen value
function maxLoot(hval,n)
{
    // base case
    if (n < 0) {
        return 0;
    }
  
    if (n == 0) {
        return hval[0];
    }
    // if current element is pick then previous cannot be
    // picked
    let pick = hval[n] + maxLoot(hval, n - 2);
    // if current element is not picked then previous
    // element is picked
    let notPick = maxLoot(hval, n - 1);
  
    // return max of picked and not picked
    return Math.max(pick, notPick);
}
  
// Driver to test above code
  
let hval = [ 6, 7, 1, 3, 8, 2, 4 ];
let n = hval.length;
document.write("Maximum loot possible : ",maxLoot(hval, n - 1));
  
  
// This code is contributed by shinjanpatra
  
</script>


Output

Maximum loot possible : 19

Time Complexity:  O(2N). Every element has 2 choices to pick and not pick
Auxiliary Space: O(2N). A recursion stack space is required of size 2n, so space complexity is O(2N).

Find the maximum possible stolen value from houses using O(n) extra space

Here, we are finding which will be the best pattern to steal a house without getting any police alert 

the approach has one edge case there will be only one/two houses then the output will be 

maximum money that is there in any house

else will be traverse for all houses and try to find the maximum amount that can get by coming from the previous house to current house

and at the end, we will just output maximum amount along the vector.

C++




#include <bits/stdc++.h>
#include <iostream>
#define int long long
using namespace std;
  
void solve(int n, vector<int>& v)
{
    vector<int> dp(n, -2);
    int maxmoney = 0;
    if (n == 1 || n == 2) {
        cout << "Maximum loot possible : ";
        cout << *max_element(v.begin(), v.end()) << endl;
        return;
    }
    dp[0] = v[0];
    dp[1] = v[1];
    for (int i = 2; i < n; i++) {
        int money = 0;
        dp[i] = v[i];
        for (int j = i - 2; j >= 0; j--) {
            money = max(money, dp[j]);
        }
        dp[i] += money;
    }
    int m = *max_element(dp.begin(), dp.end());
    cout << "Maximum loot possible : ";
    cout << m << endl;
    return;
}
signed main()
{
    // int t;cin>>t;
    // while(t--){
    int n = 7;
    vector<int> v{ 6, 7, 1, 3, 8, 2, 4 };
    solve(n, v);
    //}
    return 0;
}


Java




// Java code for the above approach
import java.util.Arrays;
import java.util.Scanner;
  
public class Main {
  public static void solve(int n, int[] v)
  {
    int[] dp = new int[n];
    Arrays.fill(dp, -2);
    int maxmoney = 0;
    if (n == 1 || n == 2) {
      System.out.print("Maximum loot possible : ");
      int max = Integer.MIN_VALUE;
      for (int i = 0; i < v.length; i++) {
        max = Math.max(v[i], max);
      }
      System.out.println(max);
      return;
    }
    dp[0] = v[0];
    dp[1] = v[1];
    for (int i = 2; i < n; i++) {
      int money = 0;
      dp[i] = v[i];
      for (int j = i - 2; j >= 0; j--) {
        money = Math.max(money, dp[j]);
      }
      dp[i] += money;
    }
    int m = Arrays.stream(dp).max().getAsInt();
    System.out.print("Maximum loot possible : ");
    System.out.println(m);
    return;
  }
  
  public static void main(String[] args)
  {
    int n = 7;
    int[] v = { 6, 7, 1, 3, 8, 2, 4 };
    solve(n, v);
  }
}
  
// This code is contributed by lokeshpotta20.


Python3




def solve(n, v):
    dp = [-2]*(n)
    maxmoney = 0
    if (n == 1 or n == 2):
        print("Maximum loot possible : ")
        print(max(v))
        return
          
    dp[0] = v[0]
    dp[1] = v[1]
    for i in range(2,n):
        money = 0
        dp[i] = v[i]
        for j in range(i-2,-1,-1):
            money = max(money, dp[j])
        dp[i] += money
    m = max(dp)
    print("Maximum loot possible :", m)
    return
  
n = 7
v = [6, 7, 1, 3, 8, 2, 4]
solve(n, v)


Javascript




function solve(n, v)
{
    let dp=new Array(n).fill(-2);
    let maxmoney = 0;
    if (n == 1 || n == 2) {
        document.write("Maximum loot possible : ");
        console.write(Math.max(...v));
        return;
    }
    dp[0] = v[0];
    dp[1] = v[1];
    for (let i = 2; i < n; i++) {
        let money = 0;
        dp[i] = v[i];
        for (let j = i - 2; j >= 0; j--) {
            money = Math.max(money, dp[j]);
        }
        dp[i] += money;
    }
    let m = Math.max(...dp);
    document.write("Maximum loot possible : ");
    document.write(m);
    return;
}
// int t;cin>>t;
// while(t--){
let n = 7;
let v = [6, 7, 1, 3, 8, 2, 4 ];
solve(n, v);
//}


C#




// C# Program to implement the above approach
  
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG {
  
    static void solve(int n, List<int> v)
    {
        List<int> dp=new List<int>();
        for(int i=0; i<n; i++)
            dp.Add(-2);
              
        int maxmoney = 0;
        if (n == 1 || n == 2) {
            Console.Write("Maximum loot possible : ");
            Console.Write(v.Max()+"\n");
            return;
        }
        dp[0] = v[0];
        dp[1] = v[1];
        for (int i = 2; i < n; i++) {
            int money = 0;
            dp[i] = v[i];
            for (int j = i - 2; j >= 0; j--) {
                money = Math.Max(money, dp[j]);
            }
            dp[i] += money;
        }
        int m = dp.Max();
        Console.Write("Maximum loot possible : ");
        Console.Write(m);
        return;
    }
    static public void Main()
    {
        // int t;cin>>t;
        // while(t--){
        int n = 7;
        List<int> v=new List<int>{ 6, 7, 1, 3, 8, 2, 4 };
        solve(n, v);
        //}
    }
}


Output

Maximum loot possible : 19

Time Complexity: O(n^2). for the worst case for the last element it will traverse over all elements of the vector. 
Space Complexity: O(n). the only used space is dp vector of o(n).

Find maximum possible stolen value from houses Dynamic Programming(Top-Down Approach):

The sub-problems can be stored thus reducing the complexity and converting the recursive solution to a Dynamic programming problem.

Follow the below steps to Implement the idea:

  • Create a DP vector of size n+1 and value -1 and variables pick and not pick
  • Create a recursive function 
    • If n < 0 possible stolen value is 0.
    • If n = 0 possible stolen value is hval[0].
    • If DP[n] != -1 possible stolen value is DP[n].
    • Set pick as pick = hval[n] +  maxLoot(hval, n-2, DP) 
    • Set not pick as notPick = maxLoot(hval, n-1, DP).
    • Set Dp[n] = max(pick, notPick) and return DP[n].

Below is the Implementation of the above approach:

C++




// CPP program to find the maximum stolen value
#include <bits/stdc++.h>
using namespace std;
  
// calculate the maximum stolen value
int maxLoot(int *hval, int n, vector<int> &dp){
    
   // base case
   if(n < 0){
           return 0 ;
   }
     
   if(n == 0){
           return hval[0] ;
   }
   // If the subproblem is already solved
   // then return its value
   if(dp[n] != -1 ){
          return dp[n] ;
   }
    
   //if current element is pick then previous cannot be picked
   int pick = hval[n] +  maxLoot(hval, n-2, dp) ;
   //if current element is not picked then previous element is picked
   int notPick = maxLoot(hval, n-1, dp)  ;
    
   // return max of picked and not picked
   return dp[n] = max(pick, notPick) ;
    
}
  
// Driver to test above code
int main()
{
    int hval[] = {6, 7, 1, 3, 8, 2, 4};
    int n = sizeof(hval)/sizeof(hval[0]);
    // Initialize a dp vector
    vector<int> dp(n+1, -1) ;
    cout << "Maximum loot possible : "
        << maxLoot(hval, n-1, dp);
    return 0;
}


Java




/*package whatever //do not write package name here */
  
// Java program to find the maximum stolen value
import java.io.*;
import java.util.Arrays;
  
class GFG {
  // Function to calculate the maximum stolen value
  static int maxLoot(int hval[], int n, int dp[])
  {
    // base case
    if (n < 0) {
      return 0;
    }
  
    if (n == 0) {
      return hval[0];
    }
    // If the subproblem is already solved
    // then return its value
    if (dp[n] != -1) {
      return dp[n];
    }
  
    // if current element is pick then previous cannot
    // be picked
    int pick = hval[n] + maxLoot(hval, n - 2, dp);
    // if current element is not picked then previous
    // element is picked
    int notPick = maxLoot(hval, n - 1, dp);
  
    // return max of picked and not picked
    return dp[n] = Math.max(pick, notPick);
  }
  
  // Driver program
  public static void main(String[] args)
  {
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = hval.length;
    int dp[] = new int[n + 1];
    Arrays.fill(dp, -1);
    System.out.println("Maximum loot possible : "
                       + maxLoot(hval, n - 1, dp));
  }
}
  
// This code is contributed by sanskar84.


Python3




# Python3 program to find the maximum stolen value
  
# calculate the maximum stolen value
  
  
def maxLoot(hval, n, dp):
  
    # base case
    if(n < 0):
        return 0
  
    if(n == 0):
        return hval[0]
  
   # If the subproblem is already solved
   # then return its value
    if(dp[n] != -1):
        return dp[n]
  
    # if current element is pick then previous cannot be picked
    pick = hval[n] + maxLoot(hval, n-2, dp)
  
    # if current element is not picked then previous element is picked
    notPick = maxLoot(hval, n-1, dp)
  
    # return max of picked and not picked
    dp[n] = max(pick, notPick)
    return dp[n]
  
  
# Driver to test above code
hval = [6, 7, 1, 3, 8, 2, 4]
n = len(hval)
  
# Initialize a dp vector
dp = [-1 for i in range(n+1)]
print("Maximum loot possible : "+str(maxLoot(hval, n-1, dp)))
  
# This code is contributed by shinjanpatra


C#




// C# program to find the maximum stolen value
using System;
public class GFG {
  
    // Function to calculate the maximum stolen value
    static int maxLoot(int[] hval, int n, int[] dp)
    {
        
        // base case
        if (n < 0) {
            return 0;
        }
  
        if (n == 0) {
            return hval[0];
        }
        // If the subproblem is already solved
        // then return its value
        if (dp[n] != -1) {
            return dp[n];
        }
  
        // if current element is pick then previous cannot
        // be picked
        int pick = hval[n] + maxLoot(hval, n - 2, dp);
        
        // if current element is not picked then previous
        // element is picked
        int notPick = maxLoot(hval, n - 1, dp);
  
        // return max of picked and not picked
        return dp[n] = Math.Max(pick, notPick);
    }
  
    static public void Main()
    {
  
        // Code
        int[] hval = { 6, 7, 1, 3, 8, 2, 4 };
        int n = hval.Length;
        int[] dp = new int[n + 1];
        Array.Fill(dp, -1);
        Console.WriteLine("Maximum loot possible : "
                          + maxLoot(hval, n - 1, dp));
    }
}
  
// This code is contributed by lokeshmvs21.


Javascript




<script>
  
// JavaScript program to find the maximum stolen value
  
// calculate the maximum stolen value
function maxLoot(hval,n,dp){
    
   // base case
   if(n < 0){
        return 0 ;
   }
     
   if(n == 0){
        return hval[0] ;
   }
   // If the subproblem is already solved
   // then return its value
   if(dp[n] != -1 ){
        return dp[n] ;
   }
    
   //if current element is pick then previous cannot be picked
   let pick = hval[n] +  maxLoot(hval, n-2, dp) ;
   //if current element is not picked then previous element is picked
   let notPick = maxLoot(hval, n-1, dp)  ;
    
   // return max of picked and not picked
   return dp[n] = Math.max(pick, notPick) ;
    
}
  
// Driver to test above code
let hval = [6, 7, 1, 3, 8, 2, 4];
let n = hval.length;
// Initialize a dp vector
let dp = new Array(n+1).fill(-1) ;
document.write("Maximum loot possible : ",maxLoot(hval, n-1, dp),"</br>");
// code is contributed by shinjanpatra
  
</script>


Output

Maximum loot possible : 19

Time Complexity: O(n). Only one traversal of the original array is needed. So the time complexity is O(n)
Space Complexity: O(n). Recursive stack space is required of size n, so space complexity is O(n).

Find maximum possible stolen value from houses Dynamic Programming(Bottom Up Approach):

The sub-problems can be stored thus reducing the complexity and converting the recursive solution to a Dynamic programming problem.

Follow the below steps to Implement the idea:

  • Create an extra space DP array to store the sub-problems.
  • Tackle the following basic cases, 
    • If the length of the array is 0, print 0. 
    • If the length of the array is 1, print the first element. 
    • If the length of the array is 2, print a maximum of two elements.
  • Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]
  • Traverse the array from the second element (2nd index) to the end of the array.
  • For every index, update dp[i] as a maximum of dp[i-2] + array[i] and dp[i-1], this step defines the two cases if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.
  • Print the value dp[n-1]

Below is the Implementation of the above approach:

C++




// CPP program to find the maximum stolen value
#include <iostream>
using namespace std;
  
// calculate the maximum stolen value
int maxLoot(int* hval, int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return hval[0];
    if (n == 2)
        return max(hval[0], hval[1]);
  
    // dp[i] represent the maximum value stolen
    // so far after reaching house i.
    int dp[n];
  
    // Initialize the dp[0] and dp[1]
    dp[0] = hval[0];
    dp[1] = max(hval[0], hval[1]);
  
    // Fill remaining positions
    for (int i = 2; i < n; i++)
        dp[i] = max(hval[i] + dp[i - 2], dp[i - 1]);
  
    return dp[n - 1];
}
  
// Driver to test above code
int main()
{
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(hval) / sizeof(hval[0]);
    cout << "Maximum loot possible : " << maxLoot(hval, n);
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to find the maximum stolen value
#include <stdio.h>
  
// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}
  
// calculate the maximum stolen value
int maxLoot(int* hval, int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return hval[0];
    if (n == 2)
        return max(hval[0], hval[1]);
  
    // dp[i] represent the maximum value stolen
    // so far after reaching house i.
    int dp[n];
  
    // Initialize the dp[0] and dp[1]
    dp[0] = hval[0];
    dp[1] = max(hval[0], hval[1]);
  
    // Fill remaining positions
    for (int i = 2; i < n; i++)
        dp[i] = max(hval[i] + dp[i - 2], dp[i - 1]);
  
    return dp[n - 1];
}
  
// Driver to test above code
int main()
{
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(hval) / sizeof(hval[0]);
    printf("Maximum loot possible : %d", maxLoot(hval, n));
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to find the maximum stolen value
import java.io.*;
  
class GFG {
    // Function to calculate the maximum stolen value
    static int maxLoot(int hval[], int n)
    {
        if (n == 0)
            return 0;
        if (n == 1)
            return hval[0];
        if (n == 2)
            return Math.max(hval[0], hval[1]);
  
        // dp[i] represent the maximum value stolen
        // so far after reaching house i.
        int[] dp = new int[n];
  
        // Initialize the dp[0] and dp[1]
        dp[0] = hval[0];
        dp[1] = Math.max(hval[0], hval[1]);
  
        // Fill remaining positions
        for (int i = 2; i < n; i++)
            dp[i]
                = Math.max(hval[i] + dp[i - 2], dp[i - 1]);
  
        return dp[n - 1];
    }
  
    // Driver program
    public static void main(String[] args)
    {
        int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
        int n = hval.length;
        System.out.println("Maximum loot possible : " + maxLoot(hval, n));
    }
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 program to find the maximum stolen value
  
# calculate the maximum stolen value
def maximize_loot(hval, n):
    if n == 0:
        return 0
    if n == 1:
        return hval[0]
    if n == 2:
        return max(hval[0], hval[1])
  
    # dp[i] represent the maximum value stolen so
    # for after reaching house i.
    dp = [0]*n
  
    # Initialize the dp[0] and dp[1]
    dp[0] = hval[0]
    dp[1] = max(hval[0], hval[1])
      
    # Fill remaining positions
    for i in range(2, n):
        dp[i] = max(hval[i]+dp[i-2], dp[i-1])
  
    return dp[-1]
  
# Driver to test above code 
def main():
  
    # Value of houses
    hval = [6, 7, 1, 3, 8, 2, 4]
  
    # number of houses
    n = len(hval)
    print("Maximum loot possible : {}".
        format(maximize_loot(hval, n)))
  
if __name__ == '__main__':
    main()


C#




// C# program to find the 
// maximum stolen value
using System;
          
class GFG 
{
   // Function to calculate the 
   // maximum stolen value
    static int maxLoot(int []hval, int n)
    {
        if (n == 0)
        return 0;
        if (n == 1)
            return hval[0];
        if (n == 2)
            return Math.Max(hval[0], hval[1]);
  
        // dp[i] represent the maximum value stolen
        // so far after reaching house i.
        int[] dp = new int[n];
  
        // Initialize the dp[0] and dp[1]
        dp[0] = hval[0];
        dp[1] = Math.Max(hval[0], hval[1]);
  
        // Fill remaining positions
        for (int i = 2; i<n; i++)
            dp[i] = Math.Max(hval[i]+dp[i-2], dp[i-1]);
  
        return dp[n-1];
    }
      
    // Driver program
    public static void Main () 
    {
        int []hval = {6, 7, 1, 3, 8, 2, 4};
        int n = hval.Length;
        Console.WriteLine("Maximum loot possible : "
                                 maxLoot(hval, n));
    }
}
  
// This code is contributed by Sam007


PHP




<?php
// PHP program to find 
// the maximum stolen value
  
// calculate the maximum
// stolen value
function maxLoot($hval, $n)
{
    if ($n == 0)
        return 0;
    if ($n == 1)
        return $hval[0];
    if ($n == 2)
        return max($hval[0], 
                   $hval[1]);
  
    // dp[i] represent the maximum 
    // value stolen so far after 
    // reaching house i.
    $dp = array();
  
    // Initialize the 
    // dp[0] and dp[1]
    $dp[0] = $hval[0];
    $dp[1] = max($hval[0], 
                 $hval[1]);
  
    // Fill remaining positions
    for ($i = 2; $i < $n; $i++)
        $dp[$i] = max($hval[$i] + 
                      $dp[$i - 2], 
                      $dp[$i - 1]);
  
    return $dp[$n - 1];
}
  
// Driver Code
$hval = array(6, 7, 1, 
              3, 8, 2, 4);
$n = sizeof($hval);
echo "Maximum loot possible : ",
             maxLoot($hval, $n);
      
// This code is contributed by aj_36
?>


Javascript




<script>
  
    // Javascript program to find 
    // the maximum stolen value
      
    // Function to calculate the 
       // maximum stolen value
    function maxLoot(hval, n)
    {
        if (n == 0)
            return 0;
        if (n == 1)
            return hval[0];
        if (n == 2)
            return Math.max(hval[0], hval[1]);
    
        // dp[i] represent the maximum value stolen
        // so far after reaching house i.
        let dp = new Array(n);
    
        // Initialize the dp[0] and dp[1]
        dp[0] = hval[0];
        dp[1] = Math.max(hval[0], hval[1]);
    
        // Fill remaining positions
        for (let i = 2; i<n; i++)
            dp[i] = Math.max(hval[i]+dp[i-2], dp[i-1]);
    
        return dp[n-1];
    }
      
    let hval = [6, 7, 1, 3, 8, 2, 4];
    let n = hval.length;
    document.write(
    "Maximum loot possible : " + maxLoot(hval, n)
    );
      
</script>


Output

Maximum loot possible : 19

Time Complexity: O(N). Only one traversal of the original array is needed. So the time complexity is O(n)
Auxiliary Space: O(N). An array is required of size n, so space complexity is O(n).

Find maximum possible stolen value from houses using constant Space:

By carefully observing the DP array, it can be seen that the values of the previous two indices matter while calculating the value for an index. To replace the total DP array with two variables.

Follow the below steps to Implement the idea:

  1. Tackle some basic cases, if the length of the array is 0, print 0, if the length of the array is 1, print the first element, if the length of the array is 2, print a maximum of two elements.
  2. Create two variables value1 and value2, value1 as array[0] and value2 as maximum of array[0] and array[1] and a variable max_val to store the answer
  3. Traverse the array from the second element (2nd index) to the end of the array.
  4. For every index, update max_val as the maximum of value1 + array[i] and value2, this step defines the two cases, if an element is selected then the previous element cannot be selected and if an element is not selected then the previous element can be selected.
  5. For every index, Update value1 = value2 and value2 = max_val
  6. Print the value of max_val

Below is the Implementation of the above approach:

C++




// C++ program to find the maximum stolen value
#include <iostream>
using namespace std;
  
// calculate the maximum stolen value
int maxLoot(int* hval, int n)
{
    if (n == 0)
        return 0;
  
    int value1 = hval[0];
    if (n == 1)
        return value1;
  
    int value2 = max(hval[0], hval[1]);
    if (n == 2)
        return value2;
  
    // contains maximum stolen value at the end
    int max_val;
  
    // Fill remaining positions
    for (int i = 2; i < n; i++) {
        max_val = max(hval[i] + value1, value2);
        value1 = value2;
        value2 = max_val;
    }
  
    return max_val;
}
  
// Driver to test above code
int main()
{
    // Value of houses
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(hval) / sizeof(hval[0]);
    cout << "Maximum loot possible : " << maxLoot(hval, n);
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to find the maximum stolen value
#include <stdio.h>
  
//Find maximum between two numbers.
int max(int num1, int num2)
{
  return (num1 > num2) ? num1 : num2;
}
  
// calculate the maximum stolen value
int maxLoot(int* hval, int n)
{
    if (n == 0)
        return 0;
  
    int value1 = hval[0];
    if (n == 1)
        return value1;
  
    int value2 = max(hval[0], hval[1]);
    if (n == 2)
        return value2;
  
    // contains maximum stolen value at the end
    int max_val;
  
    // Fill remaining positions
    for (int i = 2; i < n; i++) {
        max_val = max(hval[i] + value1, value2);
        value1 = value2;
        value2 = max_val;
    }
  
    return max_val;
}
  
// Driver to test above code
int main()
{
    // Value of houses
    int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
    int n = sizeof(hval) / sizeof(hval[0]);
    printf("Maximum loot possible : %d", maxLoot(hval, n));
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to find the maximum stolen value
import java.io.*;
  
class GFG {
    // Function to calculate the maximum stolen value
    static int maxLoot(int hval[], int n)
    {
        if (n == 0)
            return 0;
  
        int value1 = hval[0];
        if (n == 1)
            return value1;
  
        int value2 = Math.max(hval[0], hval[1]);
        if (n == 2)
            return value2;
  
        // contains maximum stolen value at the end
        int max_val = 0;
  
        // Fill remaining positions
        for (int i = 2; i < n; i++) {
            max_val = Math.max(hval[i] + value1, value2);
            value1 = value2;
            value2 = max_val;
        }
  
        return max_val;
    }
  
    // driver program
    public static void main(String[] args)
    {
        int hval[] = { 6, 7, 1, 3, 8, 2, 4 };
        int n = hval.length;
        System.out.println("Maximum loot possible : "
                           + maxLoot(hval, n));
    }
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 program to find the maximum stolen value
  
# calculate the maximum stolen value
def maximize_loot(hval, n):
    if n == 0:
        return 0
  
    value1 = hval[0]
    if n == 1:
        return value1
  
    value2 = max(hval[0], hval[1])
    if n == 2:
        return value2
  
    # contains maximum stolen value at the end
    max_val = None
  
    # Fill remaining positions
    for i in range(2, n):
        max_val = max(hval[i]+value1, value2)
        value1 = value2
        value2 = max_val
  
    return max_val
  
# Driver to test above code 
def main():
  
    # Value of houses
    hval = [6, 7, 1, 3, 8, 2, 4]
  
    # number of houses
    n = len(hval)
    print("Maximum loot possible : {}".format(maximize_loot(hval, n)))
  
if __name__ == '__main__':
    main()


C#




// C# program to find the 
// maximum stolen value
using System;
          
public class GFG 
{
    // Function to calculate the 
    // maximum stolen value
    static int maxLoot(int []hval, int n)
    {
        if (n == 0)
        return 0;
  
        int value1 = hval[0];
        if (n == 1)
            return value1;
  
        int value2 = Math.Max(hval[0], hval[1]);
        if (n == 2)
            return value2;
      
        // contains maximum stolen value at the end
        int max_val = 0;
  
        // Fill remaining positions
        for (int i = 2; i < n; i++)
        {
            max_val = Math.Max(hval[i] + value1, value2);
            value1 = value2;
            value2 = max_val;
        }
  
        return max_val;
    }
      
    // Driver program
    public static void Main () 
    {
        int []hval = {6, 7, 1, 3, 8, 2, 4};
        int n = hval.Length;
        Console.WriteLine("Maximum loot possible : " +
                                 maxLoot(hval, n));
    }
}
  
// This code is contributed by Sam007


PHP




<?php
// PHP program to find 
// the maximum stolen value
  
// calculate the 
// maximum stolen value
function maxLoot($hval, $n)
{
    if ($n == 0)
        return 0;
  
    $value1 = $hval[0];
    if ($n == 1)
        return $value1;
  
    $value2 = max($hval[0], 
                  $hval[1]);
    if ($n == 2)
        return $value2;
  
    // contains maximum 
    // stolen value at the end
    $max_val;
  
    // Fill remaining positions
    for ($i = 2; $i < $n; $i++)
    {
        $max_val = max($hval[$i] + 
                       $value1, $value2);
        $value1 = $value2;
        $value2 = $max_val;
    }
  
    return $max_val;
}
  
// Driver code
$hval = array(6, 7, 1, 3, 8, 2, 4);
$n = sizeof($hval);
echo "Maximum loot possible : ",
          maxLoot($hval, $n);
      
// This code is contributed by ajit
?>


Javascript




<script>
  
    // Javascript program to find the
    // maximum stolen value
      
    // Function to calculate the
    // maximum stolen value
    function maxLoot(hval, n)
    {
        if (n == 0)
            return 0;
   
        let value1 = hval[0];
        if (n == 1)
            return value1;
   
        let value2 = Math.max(hval[0], hval[1]);
        if (n == 2)
            return value2;
       
        // contains maximum stolen value at the end
        let max_val = 0;
   
        // Fill remaining positions
        for (let i = 2; i < n; i++)
        {
            max_val = Math.max(hval[i] + 
                               value1, value2);
            value1 = value2;
            value2 = max_val;
        }
   
        return max_val;
    }
      
    let hval = [6, 7, 1, 3, 8, 2, 4];
    let n = hval.length;
    document.write("Maximum loot possible : " 
    + maxLoot(hval, n));
      
</script>


Output

Maximum loot possible : 19

Time Complexity: O(N), Only one traversal of the original array is needed. So the time complexity is O(N).
Auxiliary Space: O(1), No extra space is required so the space complexity is constant.

This article is contributed by Atul Kumar. If you like neveropen and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments