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 (House Robber)

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

Similar Reads

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

...

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

...

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

...

Find maximum possible stolen value from houses using constant Space:

...