forked from Tanay-Gupta/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum_no._of_Jumps_to_reach_end_of_an_array.java
60 lines (49 loc) · 1.21 KB
/
minimum_no._of_Jumps_to_reach_end_of_an_array.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Java program to count Minimum number
// of jumps to reach end
class Test {
static int minJumps(int arr[])
{
if (arr.length <= 1)
return 0;
// Return -1 if not possible to jump
if (arr[0] == 0)
return -1;
// initialization
int maxReach = arr[0];
int step = arr[0];
int jump = 1;
// Start traversing array
for (int i = 1; i < arr.length; i++) {
// Check if we have reached
// the end of the array
if (i == arr.length - 1)
return jump;
// updating maxReach
maxReach = Math.max(maxReach, i + arr[i]);
// we use a step to get to the current index
step--;
// If no further steps left
if (step == 0) {
// we must have used a jump
jump++;
// Check if the current
// index/position or lesser index
// is the maximum reach point
// from the previous indexes
if (i >= maxReach)
return -1;
// re-initialize the steps to the amount
// of steps to reach maxReach from position i.
step = maxReach - i;
}
}
return -1;
}
// Driver method to test the above function
public static void main(String[] args)
{
int arr[] = new int[] { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
// calling minJumps method
System.out.println(minJumps(arr));
}
}