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]; }