213. House Robber II -Medium

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值