We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Number of Jumps to Reach the Last Index

Difficulty: Medium


Problem Description

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 maximum number of jumps you can make to reach index n - 1. If there is no way to reach index n - 1, return -1.


Key Insights

  • The problem is about finding a path in an array where each jump must satisfy a specific condition based on the target.
  • A dynamic programming approach can be utilized to keep track of the maximum number of jumps possible to reach each index.
  • The solution requires considering all valid jumps from the current index to future indices, which can be efficiently managed using a loop.

Space and Time Complexity

Time Complexity: O(n^2) - In the worst case, we may need to check each index against all subsequent indices. Space Complexity: O(n) - We maintain an array to store the maximum jumps to each index.


Solution

We can utilize dynamic programming to solve this problem. We will maintain an array dp where dp[i] represents the maximum jumps to reach index i. Initially, dp[0] is 0 since we start there, and all other indices are set to -1 to indicate they are unreachable.

For each index i, we will look for all subsequent indices j (where j > i) and check if the jump from i to j is valid based on the given condition. If it is valid, we will update dp[j] to be the maximum of its current value or dp[i] + 1. Finally, if dp[n-1] is still -1, it means we can't reach the last index, and we return -1. Otherwise, we return dp[n-1].


Code Solutions

def maxJumps(nums, target):
    n = len(nums)
    dp = [-1] * n
    dp[0] = 0  # Starting point

    for i in range(n):
        if dp[i] == -1:
            continue  # Skip unreachable indices
        for j in range(i + 1, n):
            if -target <= nums[j] - nums[i] <= target:
                dp[j] = max(dp[j], dp[i] + 1)

    return dp[n - 1] if dp[n - 1] != -1 else -1
← Back to All Questions