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])
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值