House Robber II
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
House Robber的升级版,依然是一道简单的动态规划问题。其动态转移方程同上一题。不过有个细节需要思考清楚,这题从线形变成变成了环形,首和尾不能同时选取。假设数组为nums,长度为len,如果选取了第一个元素,那么就等于是从nums[0 -> len - 2]中选择最多的money,即放弃了最后一个元素;同理,如果选择了第二个元素,那么就等于是从nums[1 -> len - 1]中选择最多的money,即放弃了第一个元素。如果还是不好理解,可以在纸上画图理解下。
代码:
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_len = len(nums)
if nums_len == 0:
return 0
elif nums_len in [1, 2, 3]:
return max(nums)
else:
return max(self.getMaxMoney(nums, 0, nums_len - 2), self.getMaxMoney(nums, 1, nums_len - 1))
def getMaxMoney(self, nums_l, left, right):
f = {} # record the max money
f[left] = nums_l[left]
f[left + 1] = nums_l[left] if nums_l[left] > nums_l[left + 1] else nums_l[left + 1]
for i in range(left + 2, right + 1):
f[i] = max(f[i - 1], f[i - 2] + nums_l[i])
return f[right]