LeetCode题库解答与分析——#231. 打家劫舍IIHouseRobberII

注意事项: 这是 打家劫舍 的延伸。

在上次盗窃完一条街道之后,窃贼又转到了一个新的地方,这样他就不会引起太多注意。这一次,这个地方的所有房屋都围成一圈。这意味着第一个房子是最后一个是紧挨着的。同时,这些房屋的安全系统与上次那条街道的安全系统保持一致。

给出一份代表每个房屋存放钱数的非负整数列表,确定你可以在不触动警报的情况下盗取的最高金额。

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.

个人思路:

这种环形可以看做两种线形结合(打家劫舍I的思路),即分为“从第一间抢到倒数第二间”或“从第二间抢到倒数第一间”,这样可以保证环形状态下不会首尾相接造成连续抢劫,比较这两种抢劫方式哪种多即可。

代码(JavaScript):

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function(nums) {
    var length=nums.length;
    if(length==1){
        return nums[0];
    }
    else if(length==0){
        return 0;
    }
    return Math.max(line_rob(nums,0,length-1),line_rob(nums,1,length));
};

var line_rob = function(nums,low,high) {
    var length = high-low;
    if(length==1){
        return nums[low];
    }
    var money = new Array(length);
    for(var i=0;i<length;i++){
        money[i] = nums[low+i];
    }   
    for(var i=2;i<length;i++){
        if(i==2){
            money[2] += money[0];
        }
        else{
            money[i] += Math.max(money[i-2], money[i-3]);
        }        
    }
    return Math.max(money[length-1],money[length-2])
};

猜你喜欢

转载自blog.csdn.net/weixin_38385524/article/details/79859614