Skip to content

Commit 8f90860

Browse files
authored
Update 1340-jump-game-v.js
1 parent 4189e0c commit 8f90860

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

1340-jump-game-v.js

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,27 @@
33
* @param {number} d
44
* @return {number}
55
*/
6-
const maxJumps = function (arr, d) {
7-
const map = {}
8-
let max = 1
9-
for (let i = 0; i < arr.length; i++) {
10-
max = Math.max(max, calc(i))
11-
}
12-
return max
6+
const maxJumps = function (arr, d, res = 1) {
7+
const dp = Array(1001).fill(0)
8+
for (let i = 0, len = arr.length; i < len; ++i)
9+
res = Math.max(res, dfs(arr, i, d))
10+
return res
1311

14-
function calc(i) {
15-
if (map[i]) return map[i]
16-
let max = 1
17-
const left = Math.max(0, i - d)
18-
for (let j = i - 1; j >= left; j--) {
19-
if (arr[j] >= arr[i]) break
20-
if (arr[j] < arr[i]) max = Math.max(max, calc(j) + 1)
21-
}
22-
const right = Math.min(arr.length - 1, i + d)
23-
for (let j = i + 1; j <= right; j++) {
24-
if (arr[j] >= arr[i]) break
25-
if (arr[j] < arr[i]) max = Math.max(max, calc(j) + 1)
26-
}
27-
map[i] = max
28-
return map[i]
12+
function dfs(arr, i, d, res = 1) {
13+
if (dp[i]) return dp[i]
14+
for (
15+
let j = i + 1;
16+
j <= Math.min(i + d, arr.length - 1) && arr[j] < arr[i];
17+
++j
18+
)
19+
res = Math.max(res, 1 + dfs(arr, j, d))
20+
for (let j = i - 1; j >= Math.max(0, i - d) && arr[j] < arr[i]; --j)
21+
res = Math.max(res, 1 + dfs(arr, j, d))
22+
return (dp[i] = res)
2923
}
3024
}
3125

26+
3227
// another
3328

3429
/**

0 commit comments

Comments
 (0)