题目一:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that 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.
这道题的大概意思是:求一个数组中不连续子数组的最大和,比如数组{1,2,3,4,5,6},那么最大不连续子数组的最大和12,即{2,4,6}。
解法一:时间复杂度为o(n),空间复杂度为o(n)。int rob(vector<int>& nums)
{
if (nums.empty())
return 0;
if (nums.size() == 1)
return nums[0];
vector<int> data(nums.size());
data[0] = nums[0];
data[1] = nums[1];
for (int i = 2; i < nums.size(); ++i)
{
int index = 0;
for (int j = 1; j <= i - 2; ++j)
{
if (data[j] > data[index])
index = j;
}
data[i] = nums[i] + data[index];
}
int max_val = data[0];
for (int i = 1; i < data.size(); ++i)
{
if (max_val < data[i])
max_val = data[i];
}
return max_val;
}
解法二:时间复杂度为o(n),空间复杂度为o(1)。int max(int a,int b)
{
if(a > b)
b = a;
return b;
}
int rob(vector<int>& nums)
{
if (nums.empty())
return 0;
int a = 0;//存储奇数位的最大值
int b = 0;//存储偶数位的最大值
for (int i = 0; i < nums.size(); ++i)
{
if ((i & 1) == 0)
{
a = max(nums[i] + a, b);
}
else
{
b = max(nums[i] + b, a);
}
}
return max(a, b);
}
题目二:
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.
题目二是题目一的扩展,题目一的子数组中任意两个数在原数组中都不连续,题目二限制条件更严格,首尾元素不能出现在子数组中,我们还是按照题目一的解题思路:我们先求出0~len-1,数组的不连续子数组的最大值,然后再求出1~len数组的不连续子数组的最大值,最后比较着两个最大值,返回两者中的最大值。代码如下:int max(int a, int b)
{
if (a > b)
b = a;
return b;
}
int robHepler(vector<int> &nums, int start, int last)
{
int a = 0;
int b = 0;
for (int i = start; i <= last; ++i)
{
if ((i & 1) == 0)
{
a = max(a + nums[i], b);
}
else
{
b = max(b + nums[i], a);
}
}
return max(a, b);
}
int rob(vector<int> &nums)
{
if (nums.empty())
return 0;
if(nums.size() == 1)
return nums[0];
return max(robHepler(nums, 0, nums.size() - 2),
robHepler(nums, 1, nums.size() - 1));
}