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.
Example
Given [3, 8, 4], return 8.
Note
注意对边界条件的判断,是否非空,是否长度为1.
Solution
public class Solution {
public long houseRobber(int[] A) {
int len = A.length;
if (A == null || len == 0) return 0;
if (len == 1) return A[0];
long[] dp = new long[len+1];
dp[0] = A[0];
dp[1] = Math.max(A[0], A[1]);
for (int i = 2; i < len; i++) {
dp[i] = Math.max(dp[i-1], dp[i-2] + A[i]);
}
return dp[len-1];
}
}