You stand on index 0 of an array nums of non-negative integers, and want to reach the last index. From index i you may jump forward by any distance from 1 up to nums[i] (a value of 0 means you can't move on from there). Return the fewest jumps that take you to the last index.
Every input is built so that the last index can be reached.
Jump from index 0 to index 2, whose 4 reaches index 6 in a single jump. Jumping as far as possible first, to index 3, would cost four jumps.
Each index lets you move just one step, so you need three jumps to cover three steps.
With one element you already stand on the last index.
Constraints
1 <= nums.length <= 10⁴0 <= nums[i] <= 10000.Think in rounds: all indices one jump can reach form a contiguous range, the indices two jumps can reach form the next range, and so on. You only need to know where each range ends.
The tempting rule is "always jump as far as you can". Example 1 shows it fails: from index 0 the longest jump lands on index 3, a 1, while the shorter jump to index 2 lands on a 4 that finishes the trip in one more jump. Where you land matters more than how far you went.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium
2