-
Notifications
You must be signed in to change notification settings - Fork 24
/
0198-house-robber.js
44 lines (35 loc) · 1.33 KB
/
0198-house-robber.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 198. House Robber
// Easy 39%
// You are a professional robber planning to rob houses along a street. Each
// house has a certain amount of money stashed, the only constraint stopping you
// from robbing each of them is that adjacent houses have security system
// connected and it will automatically contact the police if two adjacent houses
// were broken into on the same night.
// Given a list of non-negative integers representing the amount of money of each
// house, determine the maximum amount of money you can rob tonight without
// alerting the police.
// Credits:Special thanks to @ifanchu for adding this problem and creating all
// test cases. Also thanks to @ts for adding additional test cases.
/**
* @param {number[]} nums
* @return {number}
*/
const rob = function(nums) {
const n = nums.length
for (let i = 2; i < n; i++) {
nums[i] += Math.max(nums[i - 2], (nums[i - 3] || 0))
}
return n ? Math.max(nums[n - 1], (nums[n - 2] || 0)) : 0
}
;[
[5,4,3,2,1,4,2,4], // 16
[1,7,9,4], // 11
[], // 0
[0], // 0
].forEach(nums => {
console.log(rob(nums))
})
// Solution:
// 利用累积法。
// 每到一个房子i,就加上(i - 2) 和 (i - 3) 中累积的最大的那个作为当前最大收益。
// Submission Result: Accepted