|
3 | 3 | * @param {number} d
|
4 | 4 | * @return {number}
|
5 | 5 | */
|
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 |
13 | 11 |
|
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) |
29 | 23 | }
|
30 | 24 | }
|
31 | 25 |
|
| 26 | + |
32 | 27 | // another
|
33 | 28 |
|
34 | 29 | /**
|
|
0 commit comments