[LeetCode]House Robber II

来源:互联网 发布:最准的掐指算法姻缘 编辑:程序博客网 时间:2024/05/23 19:07

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[N],它只有两个可能:

  1. 抢最后那个房子,那么就不能抢第一个房子
  2. 不抢最后那个房子,那么f[N]=f[N-1]

我们只要另外用一个数组n[i]来表示不抢第一个房子的状态,结果就是max(f[N-1],n[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)          }}
0 0
原创粉丝点击