Skip to content

Commit ed7945a

Browse files
committed
update
1 parent dcbc1d9 commit ed7945a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/house-robber-ii.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function rob(nums: number[]): number {
2+
/**
3+
* One pass loop, constant space
4+
*/
5+
const N = nums.length;
6+
if (N <= 3) return Math.max(...nums); // we really don't care
7+
8+
let next2 = nums[N - 1];
9+
let next1 = Math.max(nums[N - 1], nums[N - 2]);
10+
11+
let nnext2 = nums[N - 2];
12+
let nnext1 = Math.max(nums[N - 2], nums[N - 3]);
13+
14+
for (let i = N - 3; i >= 1; i--) {
15+
const val = Math.max(nums[i] + next2, next1);
16+
next2 = next1;
17+
next1 = val;
18+
19+
const vval = Math.max(nums[i - 1] + nnext2, nnext1);
20+
nnext2 = nnext1;
21+
nnext1 = vval;
22+
}
23+
return Math.max(next1, nnext1);
24+
}

0 commit comments

Comments
 (0)