Skip to content

Commit a95873c

Browse files
authored
Create 1340-jump-game-v.js
1 parent cd3c36b commit a95873c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

1340-jump-game-v.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} arr
3+
* @param {number} d
4+
* @return {number}
5+
*/
6+
const maxJumps = function (arr, d) {
7+
const cache = new Array(arr.length)
8+
const diffs = [1, -1]
9+
const dfs = (i) => {
10+
if (cache[i]) return cache[i]
11+
let max = 0
12+
for (let diff of diffs) {
13+
for (let j = diff; Math.abs(j) <= d; j += diff) {
14+
const nextPosition = i + j
15+
const isValidJump =
16+
nextPosition >= 0 &&
17+
nextPosition < arr.length &&
18+
arr[i] > arr[nextPosition]
19+
if (isValidJump) max = Math.max(max, dfs(nextPosition))
20+
else break
21+
}
22+
}
23+
const result = max + 1
24+
cache[i] = result
25+
return result
26+
}
27+
for (let i = 0; i < arr.length; i++) dfs(i)
28+
return Math.max(...cache)
29+
}

0 commit comments

Comments
 (0)