public class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
if (nums.length == 2) {
return Math.max(nums[0], nums[1]);
}
if (nums.length == 3) {
return Math.max(nums[0], Math.max(nums[1], nums[2]));
}
int first = nums[0];
int second = Math.max(nums[0], nums[1]);
int forward = nums[1];
for (int i = 2; i < nums.length - 1; i++) {
forward = Math.max(first + nums[i], second);
first = second;
second = forward;
}
first = nums[nums.length - 1];
second = Math.max(nums[nums.length - 1], nums[nums.length - 2]);
int backward = nums[nums.length - 2];
for (int i = nums.length - 3; i > 0; i--) {
backward = Math.max(first + nums[i], second);
first = second;
second = backward;
}
return Math.max(forward, backward);
}
}