Problem of the day
Given an array of non-negative integers ‘ARR’ of length ‘N’, you are initially positioned at the array's first index.
Each element in the array represents your maximum jump length at that position.
Return the minimum number of jumps required to reach the last index.
If it is not possible to reach the last index, return -1.
Example:Input:
‘N’ = 3
‘ARR’ = [ 2, 1, 1 ]
The shortest way to reach index 2 is
Index 0 => Index 2
that requires only 1 jump.
The first line contains ‘T,’ denoting the number of test cases.
The first line of each test case contains ‘N’ denoting the size of the ‘ARR’.
The second line of each test case contains 'N' space-separated Integers denoting the ‘ARR’.
Output Format:
For each test case, Return the answer as described in the problem statement.
Output for each test case is printed on a separate line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10000
0 <= ARR [ i ] <= N
Time Limit: 1 sec
2
5
2 3 1 1 4
4
1 1 1 1
Sample Output 1:
2
3
For the first test case:-
The optimal path is:
0 => 1 => 4
For the second test case:-
0 => 1 => 2 => 3
2
5
2 3 0 1 4
3
1 0 2
2
-1
Can we use dynamic programming here?
We can use dynamic programming. We can build an array ‘DP’ of size ‘N’ where
DP [ i ] denotes the minimum number of jumps to reach index ‘i’ from index 0.
We can traverse the array from left to right for every index ‘i’ from 0 to ‘N’ - 1. For every index ‘i’, we can iterate from index ‘i’ + 1 to + ‘i’ + ARR [ i ], updating the values if jumping from index ‘i’ is more optimal.
The steps are as follows:-
function minJumps ( int N , [ int ] ARR ):
O ( N2 ), Where ‘N’ is the size of array ‘ARR’.
We are running a nested for loop with at most N X N steps in total.
Hence, the time complexity is O ( N2 ).
O ( N ).
We are using extra space to make the ‘DP’ array.
Hence, the space complexity is O ( N ).