Description
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.
Analysis
A dynamic programming problem. The key is to control the odd-and-even shift.
Code
class Solution {
public:
int rob(vector<int>& nums) {
bool oddOrNot = false;
int sum_odd = 0,sum_even = 0;
for (int i : nums){
if (oddOrNot){
oddOrNot = false;
sum_odd = max(sum_even, sum_odd + i);
}
else{
oddOrNot = true;
sum_even = max(sum_odd, sum_even + i);
}
}
return max(sum_odd,sum_even);
}
};
Appendix
- Link: https://leetcode.com/problems/house-robber/
- Run Time: 3ms