# 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:

# 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 :

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

--

--

## More from Placewit

Upskilling students for tech placements!

Love podcasts or audiobooks? Learn on the go with our new app.

## Placewit

476 Followers

Upskilling students for tech placements!