Leetcode: 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.
Analysis:
if the last one is not robbed, then you are free to choose whether to rob the first one. you can break the circle by assuming the first house is not robbed.
For example, 1 -> 2 -> 3 -> 1 becomes 2 -> 3 if 1 is not robbed.
Since every house is either robbed or not robbed and at least half of the houses are not robbed, the solution is simply the larger of two cases with consecutive houses, i.e. house i not robbed, break the circle, solve it, or house i + 1 not robbed. Hence, the following solution. I chose i = n and i + 1 = 0 for simpler coding. But, you can choose whichever two consecutive ones.
1 class Solution { 2 public int rob(int[] nums) { 3 if (nums == null || nums.length == 0) return 0; 4 if (nums.length == 1) return nums[0]; 5 return Math.max(helper(nums, 0, nums.length - 2), helper(nums, 1, nums.length - 1)); 6 } 7 8 public int helper(int[] nums, int lo, int hi) { 9 int prev2 = 0; 10 int prev1 = nums[lo]; 11 for (int i = lo + 1; i <= hi; i++) { 12 int temp = prev1; 13 prev1 = Math.max(prev1, prev2 + nums[i]); 14 prev2 = temp; 15 } 16 return prev1; 17 } 18 }