Problem 138
Jump Game II
Medium · 20 pts · Array, Greedy, Dynamic Programming
Problem
You start at index 0 of an array of N non-negative integers. From index i you can jump to any index from i + 1 to i + A[i]. The last index is always reachable. Find the minimum number of jumps needed to reach it. Think of it as a breadth-first search in levels: all indices reachable with j jumps form a range. While scanning the current range, record the farthest index reachable with one more jump; when you reach the end of the current range, take a jump and move to the next range.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the minimum number of jumps.
Constraints
1 <= N <= 10000; 0 <= A[i] <= 1000; the last index is reachable
Example input
5 2 3 1 1 4
Example output
2
Explanation
In 2 3 1 1 4, jump from index 0 to index 1, then from index 1 (value 3) straight to index 4. That is 2 jumps, and a single jump from index 0 reaches at most index 2.