這種題肯定是因為bug free的。有一點搞清楚,notrob = Math.max(rob, notrob)的原因是如果這個house不搶,它前面的house是可以搶也可以不搶的,而我們的dp每一步求出的是到這個房子所能搶到的最多的錢。所以我們要取一個最大值of rob, notrob.
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0){
return 0;
}
int rob = 0;
int notrob = 0;
for (int i = 0; i < nums.length; i++){
int curtrob = notrob + nums[i];
notrob = Math.max(rob, notrob);
rob = curtrob;
}
return Math.max(rob, notrob);
}
}