Skip to content

Commit eeaa005

Browse files
authored
Update Solution.js
1 parent 06fc7e9 commit eeaa005

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed
Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
function rob(nums) {
22
const n = nums.length;
3-
const f = Array(n + 1).fill(0);
4-
f[1] = nums[0];
5-
for (let i = 2; i <= n; ++i) {
6-
f[i] = Math.max(f[i - 1], f[i - 2] + nums[i - 1]);
7-
}
8-
return f[n];
3+
const f = Array(n).fill(-1);
4+
const dfs = i => {
5+
if (i >= n) {
6+
return 0;
7+
}
8+
if (f[i] < 0) {
9+
f[i] = Math.max(nums[i] + dfs(i + 2), dfs(i + 1));
10+
}
11+
return f[i];
12+
};
13+
return dfs(0);
914
}

0 commit comments

Comments
 (0)