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.
题意:假设所有的房子都相连组成一个圈,仍然不能取相邻的房子,那么最大收益为如何。思路:原先房子是一列,则动态规划求解出最大值,现在房子是一个圈,则第1个房子和第n个房子不能同时取,那么问题就分为两大类,有1没n的时候最大值,和有n没1的时候的最大值,即求出sum(0, n-2)与sum(1, n-1)并比较大小即可。
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.empty()){
return 0;
}
int length = nums.size();
if (length == 1)
return nums[0];
//calaulate 0 to n-2
vector<int> f(length, 0);
f[1] = nums[0];
for (int i = 2; i < length; i++){
f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]);
}
if (length == 2)
return max(nums[0], nums[1]);
//calculate 1 to n-1
vector<int> g(length, 0);
g[1] = nums[1];
for (int i = 2; i < length; i++){
g[i] = max(g[i - 1], g[i - 2] + nums[i]);
}
return max(f[length - 1], g[length - 1]);
}
};