题目描述:
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.
这是一道典型的动态规划题目。实质上是给定一个数组,寻找出数组中元素相加得到的最大结果。唯一不同的地方在于,这里选取的元素不能是相邻元素。对于这一特点,可以用求余操作来实现。
代码如下:
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
int a=0;
int b=0;
for(int i=0;i<n;i++){
if(i%2==0){
a=max(a+nums[i],b);
}
else{
b=max(a,nums[i]+b);
}
}
return max(a,b);
}
};