题目
题目 | 解题 |
---|---|
198. 打家劫舍 | 动态规划 |
213. 打家劫舍 II | 动态规划 |
337. 打家劫舍 III | 动态规划+深度优先搜索 |
解题
// javascript
var rob = function(nums) {
const n = nums.length;
if (n === 1) return nums[0];
if (n === 2) return Math.max(nums[0], nums[1]);
return Math.max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1));
};
const robRange = (nums, start, end) => {
let first = 0, second = nums[start];
let maxGain = nums[start];
for (let i = start + 1; i <= end; i++) {
let cur = first + nums[i];
cur = Math.max(cur, second);
maxGain = Math.max(maxGain, cur);
first = second;
second = cur;
}
return maxGain;
};