We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent dcbc1d9 commit ed7945aCopy full SHA for ed7945a
src/house-robber-ii.ts
@@ -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