var rob = function(nums) {
if (!Array.isArray(nums) || nums.some(isNaN)) {
throw new Error("Invalid input: nums must be an array of numbers");
}
const n = nums.length;
if (n === 0) return 0;
if (n === 1) return nums[0];
function robHelper(arr) {
let prev = 0, curr = 0;
for (let num of arr) {
let temp = Math.max(curr, prev + num);
prev = curr;
curr = temp;
}
return curr;
}
// Case 1: Do not rob the first house
let case1 = robHelper(nums.slice(1));
// Case 2: Do not rob the last house
let case2 = robHelper(nums.slice(0, n - 1));
return Math.max(case1, case2);
};
var rob = function(nums) {
if (nums.length === 0) return 0;
if (nums.length === 1) return nums[0];
if (nums.length === 2) return Math.max(nums[0], nums[1]);
let prev1 = 0,curr1=0;
let prev2 = 0,curr2=0;
for (let i = 1; i < nums.length; i++) {
let current = Math.max(prev1, curr1 + nums[i]);
curr1=prev1
prev1=current
}
for (let i = 0; i < nums.length-1; i++) {
let current = Math.max(prev2, curr2 + nums[i]);
curr2=prev2
prev2=current
}
return Math.max(prev1, prev2);
};
let nums = [1,2,3]
console.log(rob(nums))
inner loop
out loop v
标签:return,213,nums,max,II,length,let,打家劫舍,Math From: https://www.cnblogs.com/KooTeam/p/18675868