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]);
}
return Math.max(helper(nums, 0, nums.length - 2), helper(nums, 1, nums.length - 1));
}
private int helper(int[] nums, int start, int end) {
int[] res = new int[nums.length];
if (start == 0) {
res[0] = nums[0];
res[1] = Math.max(res[0], nums[1]);
} else if (start == 1) {
res[1] = nums[1];
}
for (int i = 2; i <= end; i++) {
res[i] = Math.max(res[i - 2] + nums[i], res[i - 1]);
}
return res[end];
}
}
House Robber II
最新推荐文章于 2022-11-01 19:16:12 发布