• 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.

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    public class Solution {
        public int rob(int[] nums) {
            //偷最后一家和不偷最后一家
            if(nums.length == 0) return 0;
            if(nums.length == 1) return nums[0];
            int n = nums.length;
            int[] dp1 = new int[n];
            int[] dp2 = new int[n];
         
            dp1[0] = nums[0];
            dp1[1] = Math.max(nums[1], nums[0]);
            for(int i = 2 ; i < n-1 ; i++){
                dp1[i] = Math.max(dp1[i-1] , dp1[i-2] + nums[i]);
            }
            
            dp2[n-1] = nums[n-1];
            dp2[n-2] = Math.max(nums[n-1], nums[n-2]);
            for(int i = n-3 ; i > 0 ; i--){
                dp2[i] = Math.max(dp2[i+1] , dp2[i+2] + nums[i]);
            }
            return Math.max(dp2[1] , dp1[n-2]);
        }
    }
  • 相关阅读:
    opencv-识别手写数字
    opencv-图像遍历
    533. Lonely Pixel II
    531. Lonely Pixel I
    495. Teemo Attacking
    370. Range Addition
    487. Max Consecutive Ones II
    485. Max Consecutive Ones
    414. Third Maximum Number
    90. Subsets II
  • 原文地址:https://www.cnblogs.com/joannacode/p/6108089.html
Copyright © 2020-2023  润新知