LeetCode -- House Robber II

Source: Internet
Author: User

LeetCode -- House Robber II
Description:


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.


Similar to the previous version, only the horse at the beginning and end of the array will be regarded as adjacent, that is, the horse cannot compete for both the first and last horses.


Ideas:
This article still uses DP to solve the problem, but it only needs to consider two special cases based on the 1st solution (grab 1st to give up the last one and give up 1st to grab the last one ):
1. Run the DP command on the [0, n-1] Horse to obtain max1
2. Run the DP command on the [1, n] Horse to obtain max2.


Returns the maximum values of max1 and max2.


Note: because it is a ring, when it is less than 4 horses, you only need to return the maximum value of the array.




Implementation Code:


public int Rob(int[] nums)     {        if(nums == null || nums.Length == 0)    {    return 0;    }        if(nums.Length < 4){    return nums.Max();    }        var list = new List
 
  (nums);    var first = list[0];    list.RemoveAt(0);    var max1 = Max(list);        list.Insert(0 , first);    list.RemoveAt(list.Count-1);    var max2 = Max(list);        return Math.Max(max1 , max2);    }    private int Max(IList
  
    nums)    {    var len = nums.Count;    var dp = new int[len + 1];    dp[0] = 0;    dp[1] = Math.Max(nums[0], 0);        for(var i = 2;i < len + 1; i++){    dp[i] = Math.Max(dp[i-1], dp[i-2] + nums[i-1]);    }        return dp[len];    }
  
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.