Last active
July 19, 2020 03:19
-
-
Save RP-3/431a1c7b268aeaf7c62432011f5e7049 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} arr | |
* @param {number} d | |
* @return {number} | |
*/ | |
var maxJumps = function(arr, d) { | |
const getVisitable = (i) => { | |
const options = []; | |
for(let j=i+1; j<arr.length && j <= i+d; j++){ | |
if(arr[j] >= arr[i]) break; | |
options.push(j); | |
} | |
for(let j=i-1; j>=0 && j >= i-d; j--){ | |
if(arr[j] >= arr[i]) break; | |
options.push(j); | |
} | |
return options; | |
}; | |
const memo = new Array(arr.length).fill(-1); | |
const backtrack = (i) => { | |
if(memo[i] !== -1) return memo[i]; | |
let [result, visitable] = [1, getVisitable(i)]; | |
for(let j=0; j<visitable.length; j++){ | |
result = Math.max(result, 1 + backtrack(visitable[j])); | |
} | |
return memo[i] = result; | |
}; | |
return Math.max(...arr.map((_, i) => backtrack(i)), 0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment