打家劫舍

This commit is contained in:
2020-05-29 06:32:10 +08:00
parent 95ca64dc6c
commit 46dc5e9b3d
3 changed files with 30 additions and 0 deletions

18
src/array/house-robber.js Normal file
View File

@ -0,0 +1,18 @@
/**
* @param {number[]} nums
* @return {number}
*/
export const rob = function (nums) {
if (!nums) return 0
const len = nums.length
if (len === 0) return 0
if (len === 1) return nums[0]
let first = nums[0]; let second = Math.max(nums[0], nums[1])
for (let i = 2; i < len; i++) {
const temp = second
second = Math.max(first + nums[i], second)
first = temp
}
return second
}