|
| 1 | +/** |
| 2 | + * 1340. Jump Game V |
| 3 | + * https://leetcode.com/problems/jump-game-v/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array of integers arr and an integer d. In one step you can jump from index i to index: |
| 7 | + * - i + x where: i + x < arr.length and 0 < x <= d. |
| 8 | + * - i - x where: i - x >= 0 and 0 < x <= d. |
| 9 | + * |
| 10 | + * In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for |
| 11 | + * all indices k between i and j (More formally min(i, j) < k < max(i, j)). |
| 12 | + * |
| 13 | + * You can choose any index of the array and start jumping. Return the maximum number of indices you |
| 14 | + * can visit. |
| 15 | + * |
| 16 | + * Notice that you can not jump outside of the array at any time. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} arr |
| 21 | + * @param {number} d |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var maxJumps = function(arr, d) { |
| 25 | + const n = arr.length; |
| 26 | + const memo = new Array(n).fill(0); |
| 27 | + let result = 1; |
| 28 | + |
| 29 | + for (let i = 0; i < n; i++) { |
| 30 | + result = Math.max(result, exploreJumps(i)); |
| 31 | + } |
| 32 | + |
| 33 | + return result; |
| 34 | + |
| 35 | + function exploreJumps(index) { |
| 36 | + if (memo[index]) return memo[index]; |
| 37 | + |
| 38 | + let maxJumpsFromHere = 1; |
| 39 | + |
| 40 | + for (let offset = 1; offset <= d; offset++) { |
| 41 | + const right = index + offset; |
| 42 | + if (right < n && arr[index] > arr[right]) { |
| 43 | + maxJumpsFromHere = Math.max(maxJumpsFromHere, 1 + exploreJumps(right)); |
| 44 | + } else { |
| 45 | + break; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + for (let offset = 1; offset <= d; offset++) { |
| 50 | + const left = index - offset; |
| 51 | + if (left >= 0 && arr[index] > arr[left]) { |
| 52 | + maxJumpsFromHere = Math.max(maxJumpsFromHere, 1 + exploreJumps(left)); |
| 53 | + } else { |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + memo[index] = maxJumpsFromHere; |
| 59 | + return maxJumpsFromHere; |
| 60 | + } |
| 61 | +}; |
0 commit comments