Skip to content

213.打家劫舍-ii

题解

js
function robHelper(nums, start, end) {
  const dp = new Array(nums.length).fill(0);
  dp[start] = nums[start];
  dp[start + 1] = Math.max(nums[start], nums[start + 1]);
  for (let i = start + 2; i <= end; i++) {
    dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
  }
  return dp[end];
}

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  if (nums.length === 0) return 0;
  if (nums.length === 1) return nums[0];
  const res1 = robHelper(nums, 0, nums.length - 2);
  const res2 = robHelper(nums, 1, nums.length - 1);
  return Math.max(res1, res2);
};
function robHelper(nums, start, end) {
  const dp = new Array(nums.length).fill(0);
  dp[start] = nums[start];
  dp[start + 1] = Math.max(nums[start], nums[start + 1]);
  for (let i = start + 2; i <= end; i++) {
    dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
  }
  return dp[end];
}

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  if (nums.length === 0) return 0;
  if (nums.length === 1) return nums[0];
  const res1 = robHelper(nums, 0, nums.length - 2);
  const res2 = robHelper(nums, 1, nums.length - 1);
  return Math.max(res1, res2);
};