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 5223dec commit a736c22Copy full SHA for a736c22
house-robber-ii/hyer0705.ts
@@ -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