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.
思路:变成环形屋子后,最关键的改变是数组中第一个房子受到了最后一个房子的制约,因此如果选了第一个房子,可选范围将除去最后一个房子;如果不选第一个房子,最后一个房子将在可选范围内。
稍稍修改之前house robber的方法,即可得出答案。
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int len = nums.length;
return Math.max(robHelper(nums, 0, len - 2), robHelper(nums, 1, len - 1));
}
public int robHelper(int[] nums, int start, int end) {
if (start > end) {
return 0;
}
int[] maxMoney = new int[end - start + 2];
maxMoney[1] = nums[start];
for (int index = 2, i = start + 1; i <= end; i++, index++) {
maxMoney[index] = Math.max(maxMoney[index-1], maxMoney[index-2] + nums[i]);
}
return maxMoney[end - start + 1];
}