Find maximum possible stolen value from houses

There are n houses build in a line, each of which contains some value in it. A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbours left and right side. 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: 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.

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



  • Algorithm:
    1. Create an extra space dp, DP array to store the sub-problems.
    2. 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 maximum of two elements.
    3. Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]
    4. Traverse the array from the second element to the end of array.
    5. For every index, update dp[i] as 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.
    6. Print the value dp[n-1]
  • Implementation:

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 value : " + maxLoot(hval, n));
        }
    }
      
    // Contributed by Pramod Kumar

    chevron_right

    
    

    Python

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # 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 value : {}".
            format(maximize_loot(hval, n)))
      
    if __name__ == '__main__':
        main()

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 value : "
                                     maxLoot(hval, n));
        }
    }
      
    // This code is contributed by Sam007

    chevron_right

    
    

    PHP

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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
    ?>

    chevron_right

    
    

  • Output:

    Maximum loot value : 19
    
  • Complexity Analysis:
    • Time Complexity: O(n).
      Only one traversal of original array is needed. So the time complexity is O(n)
    • Space Complexity: O(n).
      An array is required of size n, so space complexity is O(n).
  • Efficient Approach: By carefully observing the DP array, it can be seen that the values of previous two indices matter while calculating the value for an index. To replace the total DP array by two variables.

  • Algorithm:
    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 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 to the end of array.
    4. For every index, update max_val as 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
  • Implementation:

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 value : " + maxLoot(hval, n));
        }
    }
      
    // Contributed by Pramod kumar

    chevron_right

    
    

    Python

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # 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 value : {}".format(maximize_loot(hval, n)))
      
    if __name__ == '__main__':
        main()

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 value : " +
                                     maxLoot(hval, n));
        }
    }
      
    // This code is contributed by Sam007

    chevron_right

    
    

    PHP

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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 value : ",
              maxLoot($hval, $n);
          
    // This code is contributed by ajit
    ?>

    chevron_right

    
    

  • Output:
    Maximum loot value : 19
    
  • Complexity Analysis:
    • Time Complexity: O(n), Only one traversal of 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 GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Improved By : Sam007, jit_t, andrew1234