Note: This is a extension of house robber.
After robbing those houses on that street, the thief have found himself a new place for his thievery so that he would not GE T too much attention. This time, all houses at the is arranged in a circle. That's means the first house was 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 in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.
Problem Solving Ideas:
Can be decomposed into two cases: contains nums[0] and does not contain nums[0], respectively solve the maximum can be calculated, Java implementation is as follows;
public int Rob (int[] nums) {if (nums = = NULL | | nums.length = = 0) return 0;else if (nums.length <= 2) return Math.max (num S[0], nums[nums.length-1]); else if (nums.length==3) return Math.max (Nums[0], Math.max (nums[1],nums[2])); int res = 0;int [] dp = new Int[nums.length];DP [0] = nums[0];DP [2] = Nums[0] + nums[2];DP [3] = Nums[0] + nums[3];for (int i = 4; I < Nu Ms.length-1; i++) Dp[i] = Nums[i] + math.max (dp[i-2], dp[i-3]), Res=math.max (dp[nums.length-2],dp[nums.length-3]);DP [1] = nums[1];dp [2] = nums[2];DP [3] = nums[3] + nums[1];for (int i = 4; i < nums.length; i++) dp[i] = Nums[i] + math.max (dp[i-2], dp[i -3]); return Math.max (Res, Math.max (dp[nums.length-1],dp[nums.length-2)); }
Java for Leetcode 213 house Robber II