Jump Game: Minimum Jumps
Problem
You stand on index 0 of an array. The number a[i] is the longest jump you can make from index i (you may also jump less). Print the smallest number of jumps to reach the last index. The last index can always be reached.
Constraints
- 1 <= n <= 10^4
- 0 <= a[i] <= 1000
- the last index is reachable
Examples
Input
5 2 3 1 1 4
Output
2
Solutions
Think of breadth-first search by levels: all indexes reachable with k jumps form a range. One pass keeps the range end and the best next reach, so it needs O(n) time.
/*
* Problem : Fewest jumps.
* Input : The array.
* Output : The number of jumps.
* Approach: Greedy ranges
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: end is the farthest index that the current number of jumps can reach. farthest is the best next reach.
int jumps = 0;
int end = 0;
int farthest = 0;
// Step 2: The last index needs no jump from itself, so the loop stops one index before it.
for (int i = 0; i < a.length - 1; i++) {
farthest = Math.max(farthest, i + a[i]);
// Step 3: At the end of the current range, one more jump is needed. The new range goes to the best reach.
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (2)
- What is the range after 0 jumps?
- Why does the loop stop before the last index?