Skip to content

Commit 50a7da3

Browse files
committed
house-robber-ii solution (ts)
1 parent 5774844 commit 50a7da3

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

house-robber-ii/hi-rachel.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function rob(nums: number[]): number {
2+
if (nums.length === 1) return nums[0];
3+
if (nums.length === 2) return Math.max(nums[0], nums[1]);
4+
5+
function rob_linear(nums: number[]): number {
6+
const size = nums.length;
7+
const dp = new Array(size).fill(0);
8+
dp[0] = nums[0];
9+
dp[1] = Math.max(nums[0], nums[1]);
10+
for (let i = 2; i < size; i++) {
11+
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]);
12+
}
13+
return dp[dp.length - 1];
14+
}
15+
16+
return Math.max(
17+
rob_linear(nums.slice(0, nums.length - 1)),
18+
rob_linear(nums.slice(1))
19+
);
20+
}

0 commit comments

Comments
 (0)