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.
---
基于上一次写的house robber,其实这道题会比较有意思。我的思路是这道题的本质其实是,给了一个array,那么第一个element和最后一个element就不能连着,那么我们能不能分成两种array看?就是最后返回的这个抢劫的组合里,要么有第一个元素,要么有最后一个元素,反正不能同时有,那么我们就跟随上一道题的基础上,分别看nums[1:],nums[:-1]。
public class Solution {
public int rob(int[] nums) {
if(nums==null || nums.length<1)
return 0;
if(nums.length<2)
return nums[0];
if(nums.length<3)
return Math.max(nums[0],nums[1]);
int[] arr1;
int[] arr2;
arr1 = move(nums,0);
arr2 = move(nums,nums.length-1);
return Math.max(robMany(arr1), robMany(arr2));
}
private static int[] move(int[] nums, int index){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int num : nums){
list.add(num);
}
list.remove(index);
int[] ans = new int[nums.length];
for(int i=0;i<list.size();i++)
ans[i]=list.get(i);
return ans;
}
public int robMany(int[] nums){
int max = nums[0];
int[] big = new int[nums.length];
big[0] = nums[0];
big[1] = nums[1];
for(int i=2;i<nums.length;i++){
big[i] = nums[i] + max;
if(big[i-1] > max)
max = big[i-1];
}
return big[nums.length-1] > big[nums.length-2]?big[nums.length-1]:big[nums.length-2];
}
}
分享一个大神的解释:
https://leetcode.com/discuss/36544/simple-ac-solution-in-java-in-o-n-with-explanation