LeetCode题库解答与分析——#198. 打家劫舍HouseRobber

你是一个专业的强盗,计划抢劫沿街的房屋。每间房都藏有一定的现金,阻止你抢劫他们的唯一的制约因素就是相邻的房屋有保安系统连接,如果两间相邻的房屋在同一晚上被闯入它会自动联系警方

给定一个代表每个房屋的金额的非负整数列表,确定你可以在没有提醒警方的情况下抢劫的最高金额。

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

个人思路:

抢劫不能连续进行,因此会隔两间或三间进行抢劫,对每间房判断其两或三间前的钱数,取较多的与当前房屋的钱数相加,比较抢到最后两间房可抢到钱的数额,取最大值。

代码(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;
    }
    var money = new Array(length);
    for(var i=0;i<length;i++){
        money[i] = nums[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/79859474