answer:
Dynamic programming equation:
dp[i] = max(dp[i-2] + a[i],dp[i-1])
for i-th house, there are two options: 1. Take this home of a [i], then consider dp [i-2] (you can not take adjacent) 2 do not take it home. consider dp [i-1], select large.
Code:
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> dp(len + 1);
dp[0] = nums[0]; dp[1] = max(nums[0],nums[1]);
for(int i = 2; i < len; i++)
{
dp[i] = max(dp[i-2]+nums[i],dp[i-1]);
}
return dp[len-1];
}
};