Problem:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
Explanation:
你要去抢劫,但是不能在一个晚上抢紧邻的两家,且所有的家构成环,即抢了第一家就不能抢最后一家,找出能抢到最多钱的方案。
My Thinking:
My Solution:
Optimum Thinking:
第一家和最后一家只能抢其中的一家,如果我们把第一家和最后一家分别去掉,各算一遍能抢的最大值,然后比较两个值取其中较大的一个即为所求。
Optimum Solution:
(1)
class Solution {
public int rob(int[] nums) {
if(nums.length==0)
return 0;
if(nums.length==1)
return nums[0];
int maxexceptfirst=rob(nums,1,nums.length-1);
int maxexceptlast=rob(nums,0,nums.length-2);
return Math.max(maxexceptfirst,maxexceptlast);
}
public int rob(int[] nums,int left,int right){
if(right-left<=1)
return nums[left];
int[] dp=new int[right-left+1];
dp[0]=nums[left];
dp[1]=Math.max(nums[left+1],nums[left]);
for(int i=2;i<right-left+1;i++){
dp[i]=Math.max(dp[i-1],nums[i+left]+dp[i-2]);
}
return dp[right-left];
}
}
(2)
class Solution {
public int rob(int[] nums) {
if(nums.length==0)
return 0;
if(nums.length==1)
return nums[0];
int maxexceptfirst=rob(nums,1,nums.length-1);
int maxexceptlast=rob(nums,0,nums.length-2);
return Math.max(maxexceptfirst,maxexceptlast);
}
private int rob(int[] num, int left, int right) {
int include = 0, exclude = 0;
for (int j = left; j <= right; j++) {
int i = include, e = exclude;
include = e + num[j];
exclude = Math.max(e, i);
}
return Math.max(include, exclude);
}
}