您的位置:首页 > 其它

LeetCode 213 House Robber II

2016-04-14 10:48 190 查看
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.

被打劫的是一个环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。

public int rob2(int[] nums) {
if (nums.length <= 0) return 0;
if (nums.length == 1) return nums[0];

//打劫第1家到倒数第2家的最大值
int a = nums[0], b = Math.max(nums[1], nums[0]);
for (int i = 2; i < nums.length - 1; i++) {
int tmp = b;
b = Math.max(a + nums[i], b);
a = tmp;
}
if (nums.length <= 2) return b;

//打劫第2家到最后一家的最大值
int c = nums[1], d = Math.max(nums[1], nums[2]);
for (int i = 3; i < nums.length; i++) {
int tmp = d;
d = Math.max(c + nums[i], d);
c = tmp;
}
return Math.max(b, d);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: