LeetCode 98. 打家劫舍

Posted by cody1991 on August 9, 2020

简单思路:动态规划的问题,dp[i] = Math.max(dp[i-2] + cur, dp[i-1])

98. 打家劫舍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  if (nums.length === 0) return 0;
  for (let i = 1; i < nums.length; i += 1) {
    if (i == 1 && nums[i] < nums[i - 1]) {
      nums[i] = nums[i - 1];
    } else if (i > 1) {
      nums[i] = Math.max(nums[i - 2] + nums[i], nums[i - 1]);
    }
  }

  return nums[nums.length - 1];
};

console.log(rob([1, 2, 3, 1]));