美文网首页
198. House Robber

198. House Robber

作者: exialym | 来源:发表于2016-09-21 22:47 被阅读10次

    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.

    这是一道动态规划的题目,在你判断是否该抢当前房间的时候,你需要判断当前房间的钱加上截止到之前之前的房间已经抢到的钱的数目与截止到之前房间抢到的钱的数目谁比较多。

    var rob = function(nums) {
        if(nums.length === 0)
            return 0;
        if(nums.length === 1)
            return nums[0];
        // //额外储存版本
        // var take = 0;
        // var notake = 0;
        // var money = 0;
        // for (var i = 0; i<nums.length; i++) {
        //     take = notake + nums[i];
        //     notake = money;
        //     money = Math.max(take,notake);
        // }
        // return money;
        //直接使用数组储存版本
        nums[1] = Math.max(nums[0], nums[1]);
        for(var i = 2; i < nums.length; i++){
            nums[i] = Math.max(nums[i-2] + nums[i], nums[i - 1]);
            console.log(nums);
        }
        return nums[nums.length - 1];
    };
    

    相关文章

      网友评论

          本文标题:198. House Robber

          本文链接:https://www.haomeiwen.com/subject/bjxrettx.html