Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 10, 2026 16:44
Show Gist options
  • Select an option

  • Save tatsuyax25/67c9f9f463b791f0d1646a55e81c7dff to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/67c9f9f463b791f0d1646a55e81c7dff to your computer and use it in GitHub Desktop.
You are given a 0-indexed array nums of n integers and an integer target. You are initially positioned at index 0. In one step, you can jump from index i to any index j such that: 0 <= i < j < n -target <= nums[j] - nums[i] <= target Return the max
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var maximumJumps = function(nums, target) {
const n = nums.length;
// dp[i] = maximum number of jumps needed to reach index i
// Initialize all as unreachable (-Infinity)
const dp = Array(n).fill(-Infinity);
// Starting point: index 0 requires 0 jumps
dp[0] = 0;
// Try all pairs (i, j) with i < j
for (let j = 1; j < n; j++) {
for (let i = 0; i < j; i++) {
// Difference between values at the two indices
const diff = nums[j] - nums[i];
// A jump is valid if |nums[j] - nums[i]| <= target
if (Math.abs(diff) <= target) {
// Only update if i was reachable
if (dp[i] !== -Infinity) {
// Update dp[j] with the best (max) number of jumps
dp[j] = Math.max(dp[j], dp[i] + 1);
}
}
}
}
// If the last index is still unreachable, return -1
return dp[n - 1] < 0 ? -1 : dp[n - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment