您的位置:首页 > 其它

[LeetCode]House Robber II

2016-12-15 15:55 316 查看

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.

本题难度Medium。

题意

房子围城圈,抢头就不能抢尾。

DP

复杂度

时间 O(N) 空间 O(1)

思路

这道题难点在于围成圈,解决关键就在于最后那个房子的判断,实际上还是换汤不换药。设到达最后那个房子状态为
f
,它只有两个可能:

抢最后那个房子,那么就不能抢第一个房子

不抢最后那个房子,那么
f=f[N-1]


我们只要另外用一个数组
n[i]
来表示不抢第一个房子的状态,结果就是
max(f[N-1],n
)
。这里同样可以使用[LeetCode]House Robber 的优化,使用2对变量即可。

代码

public class Solution {
public int rob(int[] nums) {
//require
int N=nums.length;
if(N<2)return N==0?0:nums[0];
//a1、b1是正常的,a2、b2是不抢第一个房子
int a1=nums[0],b1=Math.max(a1,nums[1]),a2=0,b2=nums[1];
//invariant
for(int i=2;i<N;i++){
int tmp1=b1,tmp2=b2;
b1=Math.max(a1+nums[i],b1);
b2=Math.max(a2+nums[i],b2);
a1=tmp1;a2=tmp2;
}
//ensure
return Math.max(a1,b2); //注意不是max(b1,b2)
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 扩展