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.

Sample Input:

Output:

Explanation of given Test Cases :

Approach :

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)

Code :

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store