Maximum Number of Jumps to Reach the Last Index - DP [JS]

Description 

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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]