You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array
numsrepresenting the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 400
Let represent the money in houses , and let represent the maximum amount of money that can be robbed from houses . At the next house , the robber has two choices:
def rob(self, nums: List[int]) -> int:
def rob_subset(i: int) -> int:
"""Return the optimal money that we can rob from houses
in nums[i:] without alerting the police.
"""
if i >= len(nums):
# if there are no houses to rob, we can't make any money!
return 0
else:
# either rob the first house and skip the next one,
# or skip the first house and rob the rest
if i + 1 not in solutions:
solutions[i + 1] = rob_subset(i + 1)
if i + 2 not in solutions:
solutions[i + 2] = rob_subset(i + 2)
return max(nums[i] + solutions[i + 2], solutions[i + 1])
solutions = {}
return rob_subset(0)
A naive bottom-up implementation uses default values for and .
def rob(self, nums: List[int]) -> int:
memo = {
len(nums): 0,
len(nums) + 1: 0
}
for i in range(len(nums) - 1, -1, -1):
memo[i] = max(nums[i] + memo[i + 2], memo[i + 1])
return memo[0]
However, notice that calculating only requires the previous two values, so we don’t have to memoise every value.
def rob(self, nums: List[int]) -> int:
i_plus_one = 0
i_plus_two = 0
for i in range(len(nums) - 1, -1, -1):
opt_i = max(nums[i] + i_plus_two, i_plus_one)
i_plus_one, i_plus_two = opt_i, i_plus_one
return i_plus_one
Let be the number of houses. Then there is one loop with constant time iterations and iterations, so the algorithm takes time.
Since we only need to store 2 variables, the space complexity is constant.