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.
- If an element is selected then the next element cannot be selected.
- 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:
- Create an extra space dp, DP array to store the sub-problems.
- 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.
- Update dp[0] as array[0] and dp[1] as maximum of array[0] and array[1]
- Traverse the array from the second element to the end of array.
- 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.
- Print the value dp[n-1]
-
Implementation:
C++
// CPP program to find the maximum stolen value#include <iostream>usingnamespacestd;// calculate the maximum stolen valueintmaxLoot(int*hval,intn){if(n == 0)return0;if(n == 1)returnhval[0];if(n == 2)returnmax(hval[0], hval[1]);// dp[i] represent the maximum value stolen// so far after reaching house i.intdp[n];// Initialize the dp[0] and dp[1]dp[0] = hval[0];dp[1] = max(hval[0], hval[1]);// Fill remaining positionsfor(inti = 2; i<n; i++)dp[i] = max(hval[i]+dp[i-2], dp[i-1]);returndp[n-1];}// Driver to test above codeintmain(){inthval[] = {6, 7, 1, 3, 8, 2, 4};intn =sizeof(hval)/sizeof(hval[0]);cout <<"Maximum loot possible : "<< maxLoot(hval, n);return0;}chevron_rightfilter_noneJava
// Java program to find the maximum stolen valueimportjava.io.*;classGFG{// Function to calculate the maximum stolen valuestaticintmaxLoot(inthval[],intn){if(n ==0)return0;if(n ==1)returnhval[0];if(n ==2)returnMath.max(hval[0], hval[1]);// dp[i] represent the maximum value stolen// so far after reaching house i.int[] dp =newint[n];// Initialize the dp[0] and dp[1]dp[0] = hval[0];dp[1] = Math.max(hval[0], hval[1]);// Fill remaining positionsfor(inti =2; i<n; i++)dp[i] = Math.max(hval[i]+dp[i-2], dp[i-1]);returndp[n-1];}// Driver programpublicstaticvoidmain (String[] args){inthval[] = {6,7,1,3,8,2,4};intn = hval.length;System.out.println("Maximum loot value : "+ maxLoot(hval, n));}}// Contributed by Pramod Kumarchevron_rightfilter_nonePython
# Python3 program to find the maximum stolen value# calculate the maximum stolen valuedefmaximize_loot(hval, n):ifn==0:return0ifn==1:returnhval[0]ifn==2:returnmax(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 positionsforiinrange(2, n):dp[i]=max(hval[i]+dp[i-2], dp[i-1])returndp[-1]# Driver to test above codedefmain():# Value of houseshval=[6,7,1,3,8,2,4]# number of housesn=len(hval)print("Maximum loot value : {}".format(maximize_loot(hval, n)))if__name__=='__main__':main()chevron_rightfilter_noneC#
// C# program to find the// maximum stolen valueusingSystem;classGFG{// Function to calculate the// maximum stolen valuestaticintmaxLoot(int[]hval,intn){if(n == 0)return0;if(n == 1)returnhval[0];if(n == 2)returnMath.Max(hval[0], hval[1]);// dp[i] represent the maximum value stolen// so far after reaching house i.int[] dp =newint[n];// Initialize the dp[0] and dp[1]dp[0] = hval[0];dp[1] = Math.Max(hval[0], hval[1]);// Fill remaining positionsfor(inti = 2; i<n; i++)dp[i] = Math.Max(hval[i]+dp[i-2], dp[i-1]);returndp[n-1];}// Driver programpublicstaticvoidMain (){int[]hval = {6, 7, 1, 3, 8, 2, 4};intn = hval.Length;Console.WriteLine("Maximum loot value : "+maxLoot(hval, n));}}// This code is contributed by Sam007chevron_rightfilter_nonePHP
<?php// PHP program to find// the maximum stolen value// calculate the maximum// stolen valuefunctionmaxLoot($hval,$n){if($n== 0)return0;if($n== 1)return$hval[0];if($n== 2)returnmax($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 positionsfor($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_rightfilter_none -
Output:
Maximum loot value : 19
- Complexity Analysis:
-
Time Complexity:
.
Only one traversal of original array is needed. So the time complexity is O(n) -
Space Complexity:
.
An array is required of size n, so space complexity is O(n).
-
Time Complexity:
- Algorithm:
- 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.
- 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
- Traverse the array from the second element to the end of array.
- 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.
- For every index, Update value1 = value2 and value2 = max_val
- Print the value of max_val
-
Implementation:
C++
// C++ program to find the maximum stolen value#include <iostream>usingnamespacestd;// calculate the maximum stolen valueintmaxLoot(int*hval,intn){if(n == 0)return0;intvalue1 = hval[0];if(n == 1)returnvalue1;intvalue2 = max(hval[0], hval[1]);if(n == 2)returnvalue2;// contains maximum stolen value at the endintmax_val;// Fill remaining positionsfor(inti=2; i<n; i++){max_val = max(hval[i]+value1, value2);value1 = value2;value2 = max_val;}returnmax_val;}// Driver to test above codeintmain(){// Value of housesinthval[] = {6, 7, 1, 3, 8, 2, 4};intn =sizeof(hval)/sizeof(hval[0]);cout <<"Maximum loot possible : "<< maxLoot(hval, n);return0;}chevron_rightfilter_noneJava
// Java program to find the maximum stolen valueimportjava.io.*;classGFG{// Function to calculate the maximum stolen valuestaticintmaxLoot(inthval[],intn){if(n ==0)return0;intvalue1 = hval[0];if(n ==1)returnvalue1;intvalue2 = Math.max(hval[0], hval[1]);if(n ==2)returnvalue2;// contains maximum stolen value at the endintmax_val =0;// Fill remaining positionsfor(inti=2; i<n; i++){max_val = Math.max(hval[i]+value1, value2);value1 = value2;value2 = max_val;}returnmax_val;}// driver programpublicstaticvoidmain (String[] args){inthval[] = {6,7,1,3,8,2,4};intn = hval.length;System.out.println("Maximum loot value : "+ maxLoot(hval, n));}}// Contributed by Pramod kumarchevron_rightfilter_nonePython
# Python3 program to find the maximum stolen value# calculate the maximum stolen valuedefmaximize_loot(hval, n):ifn==0:return0value1=hval[0]ifn==1:returnvalue1value2=max(hval[0], hval[1])ifn==2:returnvalue2# contains maximum stolen value at the endmax_val=None# Fill remaining positionsforiinrange(2, n):max_val=max(hval[i]+value1, value2)value1=value2value2=max_valreturnmax_val# Driver to test above codedefmain():# Value of houseshval=[6,7,1,3,8,2,4]# number of housesn=len(hval)print("Maximum loot value : {}".format(maximize_loot(hval, n)))if__name__=='__main__':main()chevron_rightfilter_noneC#
// C# program to find the// maximum stolen valueusingSystem;publicclassGFG{// Function to calculate the// maximum stolen valuestaticintmaxLoot(int[]hval,intn){if(n == 0)return0;intvalue1 = hval[0];if(n == 1)returnvalue1;intvalue2 = Math.Max(hval[0], hval[1]);if(n == 2)returnvalue2;// contains maximum stolen value at the endintmax_val = 0;// Fill remaining positionsfor(inti = 2; i < n; i++){max_val = Math.Max(hval[i] + value1, value2);value1 = value2;value2 = max_val;}returnmax_val;}// Driver programpublicstaticvoidMain (){int[]hval = {6, 7, 1, 3, 8, 2, 4};intn = hval.Length;Console.WriteLine("Maximum loot value : "+maxLoot(hval, n));}}// This code is contributed by Sam007chevron_rightfilter_nonePHP
<?php// PHP program to find// the maximum stolen value// calculate the// maximum stolen valuefunctionmaxLoot($hval,$n){if($n== 0)return0;$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 positionsfor($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_rightfilter_none - Output:
Maximum loot value : 19
- Complexity Analysis:
- Time Complexity:
, Only one traversal of original array is needed. So the time complexity is O(n). - Auxiliary Space:
, No extra space is required so the space complexity is constant.
- Time Complexity:
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.
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Minimum broadcast range required by M towers to reach N houses
- Minimum cost required to connect all houses in a city
- Maximum XOR value of maximum and second maximum element among all possible subarrays
- Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible
- Find the maximum possible value of a[i] % a[j] over all pairs of i and j
- Find maximum possible value of advertising
- Find the maximum possible value of last element of the Array
- Largest possible square submatrix with maximum AND value
- Rearrange array to obtain maximum possible value of concatenation of prefix GCDs
- Maximum increase in value of Matrix to keep maximum rows and columns unchanged
- Minimum LCM and GCD possible among all possible sub-arrays
- Find the sum of maximum difference possible from all subset of a given array.
- Find the Maximum possible Sum for the given conditions
- Find a number such that maximum in array is minimum possible after XOR
- Find Maximum number possible by doing at-most K swaps
- Minimum Possible value of |ai + aj - k| for given array and k.
- Check if it is possible to reach to the index with value K when start index is given
- Maximize Sum possible by subtracting same value from all elements of a Subarray of the given Array
- Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
- Find Maximum value of abs(i - j) * min(arr[i], arr[j]) in an array arr[]

