Skip to content

Commit c5b2a31

Browse files
authored
Update Solution3.js
1 parent ea1c4bf commit c5b2a31

File tree

1 file changed

+5
-21
lines changed

1 file changed

+5
-21
lines changed
Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -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));
1+
function rob(nums) {
2+
let [f, g] = [0, 0];
3+
for (const x of nums) {
4+
[f, g] = [Math.max(f, g), f + x];
205
}
21-
22-
return ans;
6+
return Math.max(f, g);
237
}

0 commit comments

Comments
 (0)