Skip to content

Commit 3a466c1

Browse files
committed
feat: add js solution to lc problem: No.0198
1 parent 38fed5d commit 3a466c1

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

solution/0100-0199/0198.House Robber/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,34 @@ export function rob(nums: number[]): number {
288288
}
289289
```
290290

291+
#### JavaScript
292+
293+
```js
294+
export function rob(nums) {
295+
const cache = {};
296+
const n = nums.length;
297+
let ans = 0;
298+
299+
const dp = i => {
300+
if (cache[i] !== undefined) return cache[i];
301+
302+
let max = 0;
303+
for (let j = i + 2; j < n; j++) {
304+
max = Math.max(max, dp(j));
305+
}
306+
cache[i] = max + nums[i];
307+
308+
return cache[i];
309+
};
310+
311+
for (let i = 0; i < n; i++) {
312+
ans = Math.max(ans, dp(i));
313+
}
314+
315+
return ans;
316+
}
317+
```
318+
291319
<!-- tabs:end -->
292320

293321
<!-- solution:end -->

solution/0100-0199/0198.House Robber/README_EN.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,34 @@ export function rob(nums: number[]): number {
287287
}
288288
```
289289

290+
#### JavaScript
291+
292+
```js
293+
export function rob(nums) {
294+
const cache = {};
295+
const n = nums.length;
296+
let ans = 0;
297+
298+
const dp = i => {
299+
if (cache[i] !== undefined) return cache[i];
300+
301+
let max = 0;
302+
for (let j = i + 2; j < n; j++) {
303+
max = Math.max(max, dp(j));
304+
}
305+
cache[i] = max + nums[i];
306+
307+
return cache[i];
308+
};
309+
310+
for (let i = 0; i < n; i++) {
311+
ans = Math.max(ans, dp(i));
312+
}
313+
314+
return ans;
315+
}
316+
```
317+
290318
<!-- tabs:end -->
291319

292320
<!-- solution:end -->
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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));
20+
}
21+
22+
return ans;
23+
}

0 commit comments

Comments
 (0)