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 ea1c4bf commit c5b2a31Copy full SHA for c5b2a31
solution/0100-0199/0198.House Robber/Solution3.js
@@ -1,23 +1,7 @@
1
-export function rob(nums) {
2
- const cache = {};
3
- const n = nums.length;
4
- let ans = 0;
5
-
6
- const dp = i => {
7
- if (cache[i] !== undefined) return cache[i];
8
9
- let max = 0;
10
- for (let j = i + 2; j < n; j++) {
11
- max = Math.max(max, dp(j));
12
- }
13
- cache[i] = max + nums[i];
14
15
- return cache[i];
16
- };
17
18
- for (let i = 0; i < n; i++) {
19
- ans = Math.max(ans, dp(i));
+function rob(nums) {
+ let [f, g] = [0, 0];
+ for (const x of nums) {
+ [f, g] = [Math.max(f, g), f + x];
20
}
21
22
- return ans;
+ return Math.max(f, g);
23
0 commit comments