zoukankan      html  css  js  c++  java
  • 213. House Robber II

    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.

    此题和House Robber的不同在于,这个是首尾相连的,需要多考虑一步,当没选中第一个房子的时候可以选择最后一个房子,而当选中第一个房子的时候不可以选择最后一个房子。做法是把数组分成两个部分,然后求这两个部分最大值进行比较,代码如下:

    public class Solution {

        public int rob(int[] nums) {

            if(nums.length==0) return 0;

            if(nums.length==1) return nums[0];

            if(nums.length==2) return Math.max(nums[0],nums[1]);

            if(nums.length==3) return Math.max(nums[0],Math.max(nums[1],nums[2]));

            return Math.max(helper(Arrays.copyOfRange(nums,0,nums.length-1)),helper(Arrays.copyOfRange(nums,1,nums.length)));

        }

        public int helper(int[] nums){

            int[] dp = new int[nums.length];

            dp[0] = nums[0];

            dp[1] = Math.max(nums[0],nums[1]);

            for(int i=2;i<nums.length;i++){

                dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);

            }

            return dp[nums.length-1];

        }

    }

    这个代码初始值要多判断很多步,下面来一个简练的:

    public class Solution {

        public int rob(int[] nums) {

            if(nums.length==0) return 0;

            if(nums.length==1) return nums[0];

            return Math.max(helper(nums,0,nums.length-2),helper(nums,1,nums.length-1));

        }

        public int helper(int[] nums,int start,int end){

            int include = 0;

            int exclude = 0;

            for(int j=start;j<=end;j++){

                int i=include,e=exclude;

                include = e+nums[j];

                exclude = Math.max(i,e);

            }

            return Math.max(include,exclude);

        }

    }

  • 相关阅读:
    如何在.netcore 上实现 Rbac 权限管理
    socket编程之TCP开发中的PEEK_MSG的使用与见解
    简述单例模式的一些优缺点及其评价
    排查线上内存泄漏,RingBufferLogEvent类内存占用过高,skyWalking内存占用过高
    Centos7安装docker(报错:container-selinux >= 2:2.74)
    JSP3.4
    Java SM2加密、解密、签名、验签
    获取properties文件中的
    五种生成唯一id方式的对比
    SpringBoot 改造成 https访问
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357869.html
Copyright © 2011-2022 走看看