-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0198-house-robber.js
103 lines (82 loc) · 2.35 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Brute Force - DFS
* Time O(2^N) | Space O(N)
* https://leetcode.com/problems/house-robber/
* @param {number[]} nums
* @return {number}
*/
var rob = (nums, i = 0) => {
const isBaseCase = nums <= i;
if (isBaseCase) return 0;
const [ next, nextNext ] = [ (i + 1), (i + 2) ];
const right = nums[i];
const mid = rob(nums, next); /* Time O(2^N) | Space O(N) */
const left = rob(nums, nextNext);/* Time O(2^N) | Space O(N) */
const house = left + right;
return Math.max(house, mid);
};
/**
* DP - Top Down
* Array - Memoization
* Time O(N) | Space O(N)
* https://leetcode.com/problems/house-robber/
* @param {number[]} nums
* @return {number}
*/
var rob = (nums, i = 0, memo = initMemo(nums)) => {
const isBaseCase = nums.length <= i;
if (isBaseCase) return 0;
const hasSeen = 0 <= memo[i];
if (hasSeen) return memo[i];
const [ next, nextNext ] = [ (i + 1), (i + 2) ];
const right = nums[i];
const mid = rob(nums, next, memo); /* Time O(N) | Space O(N) */
const left = rob(nums, nextNext, memo);/* Time O(N) | Space O(N) */
const house = left + right;
memo[i] = Math.max(mid, house); /* | Space O(N) */
return memo[i];
};
const initMemo = (nums) => Array(nums.length + 1).fill(-1);
/**
* DP - Bottom Up
* Array - Tabulation
* Time O(N) | Space O(N)
* https://leetcode.com/problems/house-robber/
* @param {number[]} nums
* @return {number}
*/
var rob = (nums) => {
if (!nums.length) return 0;
const tabu = initTabu(nums);
for (let i = 1; i < nums.length; i++) {/* Time O(N) */
const right = nums[i];
const mid = tabu[i];
const left = tabu[i - 1];
const house = left + right;
tabu[i + 1] = Math.max(mid, house); /* Space O(N) */
}
return tabu[nums.length]
};
const initTabu = (nums) => {
const tabu = Array(nums.length + 1).fill(0);
tabu[1] = nums[0];
return tabu;
}
/**
* DP - Bottom Up
* Time O(N) | Space O(1)
* https://leetcode.com/problems/house-robber/
* @param {number[]} nums
* @return {number}
*/
var rob = (nums) => {
if (!nums.length) return 0;
let [ left, mid ] = [ 0, 0 ];
for (const right of nums) {/* Time O(N) */
const temp = mid;
const house = left + right;
mid = Math.max(mid, house);
left = temp;
}
return mid;
};