Question
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.
这是House Robber的拓展题。现在要抢劫的房间排列成了一个圆,这意味着第一间房和最后一间房是相邻的,安全系统仍然和之前一样(即不能抢劫相邻房间)。给出一个非负整数列表,它代表每个房间的可抢劫的钱数,请你确定在不触发安全系统的前提下,你可以抢劫的最大钱数。
Example
None
Solution
动态规划解。相比于之前的题目,这里唯一的区别就是圆,和之前的情况相比,变成圆后多了一个限制就是当你抢劫第一个房间时,就不能再抢劫最后一个房间了,为了转化成原先题目的情况(呈直线排列),我们只需考虑两种情况即
- 抢劫第二间–最后一间房间所能抢到的最多的钱
- 抢劫第一间–倒数第二间房间所能抢到的最多的钱
这样每一种情况的解法仍然和原题一样,只需最后比较哪种情况抢的钱最多即可
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] # 抢夺范围:从第一个房间到倒数第二个房间 dp = [0] * len(nums) for index in range(len(nums) - 1): if index == 0: dp[index] = nums[index] elif index == 1: dp[index] = max(nums[index], nums[index - 1]) else: dp[index] = max(dp[index - 2] + nums[index], dp[index - 1]) max_rob = dp[-2] # 最后一间房不更新 # 抢夺范围:从第二个房间到最后一个房间 dp = [0] * len(nums) for index in range(1, len(nums)): if index == 1: dp[index] = nums[index] elif index == 2: dp[index] = max(nums[index], nums[index - 1]) else: dp[index] = max(dp[index - 2] + nums[index], dp[index - 1]) # 返回收益最大那个 return max(dp[-1], max_rob)