Minimum number of jumps
Given an array of integers where each element represents the max number of steps that can be made forward from that element. The task is to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then there is no way to move from there.
Input:
The first line is T, total number of test cases.
In the following 2*T lines,
Each test case has two lines.
First line is a number n denoting the size of the array.
Next line contains the sequence of integers a1, a2, ..., an
Output:
For each test case, in a new line,
print the minimum number of jumps.
If it's not possible to reach the end the print -1
Example:
Input:
1
11
1 3 5 3 1 2 6 0 6 2 4
Output:
4
Explanation:
Let's first use greedy method.
According to greedy,
At first jump,
it will move from index 0 to 1
(arr[0]=1, so only 1 step jump is allowed)
At second jump,
It will move from index 1 to 4
(arr[1]=3, so only 3 step jump is allowed)
At third jump,
it will move from index 4 to 6
(arr[4]=2, so only 2 step jump is allowed)
Now arr[6]=0, so no more jump possible. It would result -1.
But, it's not the result. Thus, greedy fails.
Since, the array value is maximum jump possible we have to check for all options up to maximum jumps. Obviously, a recursive function which would generate many overlapping sub problems. Let's check how we can solve the above example using recursion.
After first jump (in this case only one move possible)
After second jump (I only took the best child (on solution path) of the recursion tree, you can try all)
After third jump (I only took the best child (on solution path) of the recursion tree, you can try all)
After fourth jump (That's end)
So, answer is 4.
Let's check the DP approach to solve the above problem.
C++ Implementation:
Output