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.
Example:
Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.
解释下题目:
与198类似,加了一个头尾不能同时抢的条件
1. 小聪明
实际耗时:0ms
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
} else if (nums.length == 1) {
return nums[0];
}
// ensure that the length of array is 2 or more
return Math.max(robHelp(Arrays.copyOfRange(nums, 1, nums.length)), robHelp(Arrays.copyOfRange(nums, 0, nums.length - 1)));
}
public int robHelp(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int[][] dp = new int[nums.length][2];
//init
dp[0][0] = 0;
dp[0][1] = nums[0];
for (int i = 1; i < nums.length; i++) {
// if robber do not rob the house
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
// robber rob the house
dp[i][1] = dp[i - 1][0] + nums[i];
}
return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]);
}
其实就是调用了198那题的解法,然后既然加了头尾不能同时抢,那我分两次呗,一次是[0,n-1],另外一次是[1,n],然后取两者中比较大的那个就好了。
网友评论