213. House Robber II
Posted apanda009
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章