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

`410 2 3 11`

Output:

`21`

# 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 132. [10, 11]: a total loot of 213. [2, 11]: a total loot of 134. [10]: a total loot of 105. [2]: a total loot of 26. [3]: a total loot of 37. [11]: a total loot of 11We 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.`

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

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

--

--

## More from Placewit

Upskilling students for tech placements!

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