Skip to content

Commit 543425a

Browse files
committed
feat: house-rober-ii
1 parent e10ec05 commit 543425a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

house-robber-ii/gwbaik9717.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number}
7+
*/
8+
var rob = function (nums) {
9+
if (nums.length === 1) {
10+
return nums[0];
11+
}
12+
13+
// include first
14+
const dp1 = Array.from({ length: nums.length + 1 }, () => 0);
15+
dp1[1] = nums[0];
16+
17+
// exclude first
18+
const dp2 = Array.from({ length: nums.length + 1 }, () => 0);
19+
20+
for (let i = 2; i <= nums.length; i++) {
21+
dp1[i] = Math.max(dp1[i - 2] + nums[i - 1], dp1[i - 1]);
22+
dp2[i] = Math.max(dp2[i - 2] + nums[i - 1], dp2[i - 1]);
23+
}
24+
25+
return Math.max(dp1.at(-2), dp2.at(-1));
26+
};

0 commit comments

Comments
 (0)