首页 > 代码库 > 213. House Robber II
213. House Robber II
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 打家劫舍的拓展,现在房子排成了一个圆圈,则如果抢了第一家,就不能抢最后一家,因为首尾相连了,所以第一家和最后一家只能抢其中的一家,或者都不抢,那我们这里变通一下,如果我们把第一家和最后一家分别去掉,各算一遍能抢的最大值,然后比较两个值取其中较大的一个即为所求。那我们只需参考之前的House Robber 打家劫舍中的解题方法,然后调用两边取较大值,代码如下:
public int rob(int[] nums) { if (nums == null || nums.length == 0) return 0; if (nums.length == 1) return nums[0]; int robNo = 0, robYes = nums[0]; for (int i = 1; i < nums.length - 1; i++) { int temp = robNo; robNo = Math.max(robNo, robYes); robYes = temp + nums[i]; } int ans = Math.max(robNo, robYes); robNo = 0; robYes = nums[1]; for (int i = 2; i < nums.length; i++) { int temp = robNo; robNo = Math.max(robNo, robYes); robYes = temp + nums[i]; } ans = Math.max(Math.max(robNo, robYes), ans); return ans; }
213. House Robber II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。