题目描述:
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.
题目解析:
简单的动态规划,与期中考的最小和那题类似。状态转移方程为:
sum[i] = max(sum[i-3] + nums[i],max(sum[i-2] + nums[i],sum[i-1]));
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size() == 0)
return 0;
if(nums.size() == 1)
return nums[0];
if(nums.size() == 2)
return max(nums[0],nums[1]);
if(nums.size() == 3)
return max(nums[1],nums[0] + nums[2]);
vector<int> sum(nums.size(),0);
sum[0] = nums[0];
sum[1] = nums[1];
sum[2] = max(nums[0] + nums[2],nums[1]);
for(int i = 3;i < nums.size();++i)
{
sum[i] = max(sum[i-3] + nums[i],max(sum[i-2] + nums[i],sum[i-1]));
}
return max(sum[nums.size() - 1],sum[nums.size() - 2]);
}
};