Maximum Number of Jumps to Reach the Last Index - DP [JS]
Solution: DP
Populate dp
, where dp[i] = maximum number of jumps to reach nums[i] from nums[0]
.
For each nums[j]
, go through each nums[i]
where i < j
, and if -target <= nums[j] - nums[i] <= target
, then record dp[j] = Math.max(dp[j], 1 + dp[i])
.
At the end, return dp[n - 1]
.
Time Complexity: O(n^2)
Space Complexity: O(n)
var maximumJumps = function(nums, target) {
let n = nums.length, dp = Array(n).fill(-Infinity);
dp[0] = 0;
for (let j = 1; j < n; j++) {
for (let i = 0; i < j; i++) {
if (nums[j] - nums[i] <= target && nums[j] - nums[i] >= -target) {
dp[j] = Math.max(dp[j], 1 + dp[i]);
}
}
}
return dp[n - 1] === -Infinity ? -1 : dp[n - 1];
};
Comments
Post a Comment