Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active July 19, 2020 03:19
Show Gist options
  • Save RP-3/431a1c7b268aeaf7c62432011f5e7049 to your computer and use it in GitHub Desktop.
Save RP-3/431a1c7b268aeaf7c62432011f5e7049 to your computer and use it in GitHub Desktop.
/**
* @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