Problem Description
Given a 0-indexed array of integers and an integer target, start at index 0 and try to reach index n - 1. In one jump from index i to index j (with i < j), you can only jump if the difference between nums[j] and nums[i] is between -target and target (inclusive on both ends). Return the maximum number of jumps that can be made to reach index n - 1. If it is not possible to reach the last index, return -1.
Key Insights
- This is essentially a longest path problem on a Directed Acyclic Graph (DAG) because you can only jump forward.
- Use dynamic programming where dp[i] represents the maximum number of jumps required to reach index i.
- Start with dp[0] initialized to 0 and use the condition -target <= nums[j] - nums[i] <= target to update the dp value for j from i.
- The answer will be dp[n-1] if it was updated; otherwise, return -1 if the last index is unreachable.
Space and Time Complexity
Time Complexity: O(n^2) where n is the length of the array. Space Complexity: O(n) for the dp array.
Solution
We solve the problem using a dynamic programming approach by iterating through the array and, for each index, checking all subsequent indices we can jump to while satisfying the given difference condition. For each valid jump from index i to j, we update dp[j] as the maximum of its current value and dp[i] + 1. Finally, if the last index has been reached, we return the dp value, otherwise we return -1.