Skip to content

Commit a736c22

Browse files
committed
house robber II solution
1 parent 5223dec commit a736c22

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

house-robber-ii/hyer0705.ts

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(1)
3+
function rob(nums: number[]): number {
4+
const n = nums.length;
5+
6+
if (n === 1) return nums[0];
7+
if (n === 2) return Math.max(nums[0], nums[1]);
8+
9+
const getLinearRob = (start: number, end: number) => {
10+
let prev2 = 0;
11+
let prev1 = 0;
12+
13+
for (let i = start; i <= end; i++) {
14+
const current = Math.max(prev1, prev2 + nums[i]);
15+
prev2 = prev1;
16+
prev1 = current;
17+
}
18+
19+
return prev1;
20+
};
21+
22+
let case1 = getLinearRob(0, n - 2);
23+
let case2 = getLinearRob(1, n - 1);
24+
25+
return Math.max(case1, case2);
26+
}

0 commit comments

Comments
 (0)