# 198. House Robber

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 tonightwithout alerting the police.

Credits:
Special thanks to@ifanchufor adding this problem and creating all test cases. Also thanks to@ts for adding additional test cases.

Thoughts

1. one looking ahead: not only considering whether to include or exclude this house, but also considering whether to include or exclude the previous house.

Code ( a , b alternating updates)

``````class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
int a = 0, b= 0;
for(int i = 0 ; i < n; i++){
if(i%2 == 0){
a = max(b, a + nums[i]);
}
else{
b = max(a, b + nums[i]);
}
}

return max(a,b);
}
};
``````

Code ()

``````class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
int a = 0, e= 0;
for(int i = 0 ; i < n; i++){
int tmp = a;
// update current a and e
a = e + nums[i];
e = max(tmp, e); // whether to include previous house or exclude
}

return max(a,e);
}
};
``````