- #1
FallenApple
- 566
- 61
Homework Statement
This is a leetcode question.
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.
Homework Equations
The constraint is two houses cannot be robbed.
The Attempt at a Solution
Actually, this is a solution I found online.
Code:
public int rob(int[] num) {
if(num==null || num.length == 0)
return 0;
int even = 0;
int odd = 0;
for (int i = 0; i < num.length; i++) {
if (i % 2 == 0) {
even += num[i];
even = even > odd ? even : odd;
} else {
odd += num[i];
odd = even > odd ? even : odd;
}
}
return even > odd ? even : odd;
}
The code is in Java. I'm not sure why the even and odd "pointers" need to switch. How does this solve the problem? We know they cannot rob two houses in a row. But how does this relate to evens and odds? If what is considered even and odd constantly switches, then what is the purpose of giving them the names in the first place?