Example 1
- Input
- nums = [2, 3, 1, 1, 4]
- Output
- 2
The path 0 -> 1 -> 4 uses two jumps. One jump cannot reach index 4 because nums[0] = 2, so two is the minimum.
Given an array where each element caps how far you can jump forward, find the fewest jumps needed to travel from the first index to the last one. Reaching the end is always possible.
You are given a 0-indexed array nums where nums[i] is the maximum forward jump length from index i. Starting at index 0, reach index n - 1 in as few jumps as possible.
The test cases guarantee the last index is reachable. For nums = [2, 3, 1, 1, 4] the answer is 2: jump from index 0 to 1, then from 1 to 4.
1 <= nums.length <= 10^40 <= nums[i] <= 1000The path 0 -> 1 -> 4 uses two jumps. One jump cannot reach index 4 because nums[0] = 2, so two is the minimum.
The zero at index 2 is a trap for a path landing there, but 0 -> 1 -> 4 skips it. Index 4 lies beyond the first jump range [1, 2], proving that the two-jump path is optimal.
The first index is already the last index. No move is needed, even though its jump length is zero.
A jump length is a maximum, so landing closer can set up a better next jump. In Example 1, jumping straight from index 0 to 2 needs three jumps overall, while landing at 1 reaches index 4 in two. Instead of committing to one landing, keep the whole group of indices reachable with the same minimum jump count. After one jump that group is [1, 2]; either member may launch the next jump. The best reach among them is 1 + 3 = 4, so two jumps suffice.
Reveal Brute Force DP: intuition, complexity, and code
[0], where zero jumps already stand on the last index.[5, 1, 1, 1], for an answer of 1.[2, 3, 0, 1, 4].n - 1 jumps; every window advances by exactly one index.[1000, 0], still gives one jump and must not trigger an out-of-range scan.0 -> 2 -> 3 -> 4 in three jumps, while 0 -> 1 -> 4 needs two.Integer.MAX_VALUE before checking reachability causes overflow and a false minimum.When every edge costs one, expand the reachable frontier wave by wave instead of pricing individual paths.