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.
题意:
给出一个nums的vector,从中选取一些数字,不能连续选择两个,最后使得所选取的数字之和最大。
解法:
DP,状态转移 方程:mmax[i]=max(mmax[i-2]+num[i], mmax[i-1])。
代码:
class Solution {
public:
int rob(vector<int>& nums) {
int len=nums.size();
if(len==0) return 0;
if(len==1) return nums[0];
vector<int> mmax;
mmax.push_back(nums[0]);
mmax.push_back(max(nums[0], nums[1]));
for(int i=2; i<len; i++){
mmax.push_back(max(nums[i]+mmax[i-2], mmax[i-1]));
}
return mmax[len-1];
}
};