Intermediate Level
Implement the houseRobberMaximumAmount method that returns the maximum amount that can be robbed without choosing adjacent houses.
The input contains an integer array nums and its length size. Each value represents the amount of money in one house arranged in a straight line.
Your task is to return the maximum amount that can be robbed without robbing two adjacent houses.
For example, from [2,7,9,3,1], the best choice is 2 + 9 + 1 = 12.
Use dynamic programming to decide the best result at each house.
For every house, there are two choices: skip it and keep the previous best amount, or rob it and add its money to the best amount from two houses before.
Keep only two previous values instead of storing the full DP array. This gives the same result with constant extra space.
Pseudocode:
function houseRobberMaximumAmount(nums, size):
prevTwo = 0
prevOne = 0
for each money in nums:
take = prevTwo + money
skip = prevOne
current = max(take, skip)
prevTwo = prevOne
prevOne = current
return prevOne