Problem:
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
Analysis:
Solutions:
C++:
int rob(vector<int> &num) {
if(num.empty())
return 0;
if(num.size() == 1)
return num[0];
if(num.size() == 2)
return (num[0] > num[1] ? num[0] : num[1]);
int first_max = num[0] > num[1] ? num[0] : num[1];
int second_max = num[0] < num[1] ? num[0] : num[1];
int first_max_index = num[0] > num[1] ? 0 : 1;
for(int i = 2; i < num.size(); ++i) {
if(num[i] == 0)
continue;
if(i > first_max_index + 1) {
second_max = first_max;
first_max += num[i];
first_max_index = i;
} else {
if(first_max < second_max + num[i]) {
int temp = first_max;
first_max = second_max + num[i];
second_max = temp;
first_max_index = i;
} else
second_max = second_max + num[i];
}
}
return first_max;
}
Java
:
Python: