#C14821. Minimum Number of Jumps
Minimum Number of Jumps
Minimum Number of Jumps
You are given an array of n non-negative integers, where each integer represents the maximum number of steps that can be jumped forward from that position. Your task is to determine the minimum number of jumps required to reach the last index of the array. If it is not possible to reach the end, return -1.
Formally, given an array \(a[0 \ldots n-1]\), you need to compute the minimum number of jumps \(j\) such that starting at index 0, you can reach index \(n-1\) by a sequence of jumps. At each index \(i\), you are allowed to jump to any index \(k\) where \(i < k \leq i + a[i]\). The goal is to minimize \(j\).
Note: If the array consists of a single element, the answer is 0.
This problem can be solved efficiently using a greedy approach.
inputFormat
The input is read from standard input (stdin) and consists of two lines:
- The first line contains a single integer \(n\) representing the number of elements in the array.
- The second line contains \(n\) space-separated non-negative integers representing the array \(a\).
outputFormat
Output a single integer which is the minimum number of jumps required to reach the end of the array. If it is not possible to reach the end, output -1.
## sample5
2 3 1 1 4
2
</p>