Fewest Jumps to the End or Stuck
Problem statement
You start at index 0 of the array nums. From index i you may jump forward by any number of steps from 1 to nums[i] (a value of 0 means you cannot move from there).
Return the fewest jumps needed to reach the last index. If the last index cannot be reached, return -1. If the array has one element, you are already there and the answer is 0.
Function
minJumps(nums: int[]) → intExamples
Example 1
nums = [2,4,1,1,0,2]return = 2From index 0 jump 1 step to index 1, then 4 steps to index 5: 2 jumps. Jumping as far as possible from index 0 (to index 2) leads through index 3 to the 0 at index 4 and gets stuck there.
Example 2
nums = [1,0,3]return = -1Index 0 reaches only index 1, whose value is 0, so index 2 can never be reached: -1.
Example 3
nums = [5]return = 0With one element you are already at the end: 0 jumps.
Constraints
1 <= nums.length <= 30000 <= nums[i] <= 3000