美文网首页
213. House Robber II

213. House Robber II

作者: exialym | 来源:发表于2016-09-23 13:57 被阅读19次

    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) {
        var help = function(nums) {
            if(nums.length === 0)
                return 0;
            if(nums.length === 1)
                return nums[0];
            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]);
            }
            return nums[nums.length - 1];
        };
        var num = nums.length;
        if (num===1) 
            return nums[0];
        return Math.max(help(nums.slice(0,num-1)),help(nums.slice(1,num)));
    };
    

    相关文章

      网友评论

          本文标题:213. House Robber II

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