Skip to content

Commit 1058511

Browse files
committed
Feat: 213. House Robber II
1 parent bf1cca5 commit 1058511

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

house-robber-ii/HC-kang.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* https://leetcode.com/problems/house-robber-ii
3+
* T.C. O(n)
4+
* S.C. O(1)
5+
*/
6+
function rob(nums: number[]): number {
7+
if (nums.length === 1) return nums[0];
8+
if (nums.length === 2) return Math.max(nums[0], nums[1]);
9+
if (nums.length === 3) return Math.max(nums[0], nums[1], nums[2]);
10+
11+
function robHelper(nums: number[]): number {
12+
let prev = 0;
13+
let curr = 0;
14+
for (let i = 0; i < nums.length; i++) {
15+
const temp = curr;
16+
curr = Math.max(prev + nums[i], curr);
17+
prev = temp;
18+
}
19+
return curr;
20+
}
21+
22+
const robFirst = robHelper(nums.slice(0, nums.length - 1));
23+
const robLast = robHelper(nums.slice(1));
24+
25+
return Math.max(robFirst, robLast);
26+
}

0 commit comments

Comments
 (0)