Loot Houses — Asked in Samsung and Amazon Interview
Problem Statement :
A thief wants to loot houses. He knows the amount of money in each house. He cannot loot two consecutive houses. Find the maximum amount of money he can loot.
The first line of input contains a single integer ’N’ denoting the total number of houses.
The second line of input contains ’N’ single space-separated integers, denoting the amount of money in every ‘i-th’ house.
10 2 3 11
Explanation of given Test Cases :
Since the thief cant loot two consecutive houses, the ways in which he may loot are:
1. [10, 3]: a total loot of 13
2. [10, 11]: a total loot of 21
3. [2, 11]: a total loot of 13
4. : a total loot of 10
5. : a total loot of 2
6. : a total loot of 3
7. : a total loot of 11
We can't neglect the option to loot just either of the houses if it yields the maximum loot.
From all the possible seven ways, the second option yields the maximum loot amount and hence the answer.
We can use dynamic programming to optimize our recursive approach but that would give us space complexity of O(N) so we will use a space optimized DP to bring down the space complexity.
Consider building the result array in a bottom-up fashion (computing the result for smaller to larger numbers of houses). We can observe that if we’re at the ith house, we only require the results for the (i — 1)th and the (i — 2)th houses. Hence, instead of maintaining a whole array, we simply keep track of the last two results obtained.
Time Complexity: O(N)
Space Complexity: O(1)