• 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);

        }

    }

  • 相关阅读:
    Rust 总章
    GO 总章
    vue引入d3
    echarts地图修改高亮颜色及区域界线颜色
    vue+element 树形穿梭框组件
    element表格上下固定,内容高度自适应
    echarts在dialog弹框中不显示的解决方案
    echarts 饼图给外层加边框
    selenium等待元素出现
    Pycharm永久激活
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357869.html
Copyright © 2020-2023  润新知