Skip to content

Commit 9fc3a9e

Browse files
minimum jumps
1 parent d12a3f8 commit 9fc3a9e

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

GeeksForGeeks/minimum_Jumps.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
import java.util.*;
3+
4+
public class minimum_Jumps {
5+
6+
public static void main(String[] args){
7+
8+
Scanner sc = new Scanner(System.in);
9+
int n = sc.nextInt();
10+
int[] arr = new int[n];
11+
for(int i = 0; i < n; i++){
12+
arr[i] = sc.nextInt();
13+
}
14+
minJumps(arr, n);
15+
sc.close();
16+
17+
}
18+
static void minJumps(int[] arr, int n){
19+
int[] jumps = new int[n];
20+
int min;
21+
jumps[n-1] = 0;
22+
for(int i = n-2; i >= 0; i--){
23+
// If arr[i] is 0 then arr[n-1]
24+
// can't be reached from here
25+
if(arr[i]==0){
26+
jumps[i] = Integer.MAX_VALUE;
27+
// If we can directly reach to
28+
// the end point from here then
29+
// jumps[i] is 1
30+
}else if(arr[i] >= n-i-1){
31+
jumps[i] = 1;
32+
}else{
33+
min = Integer.MAX_VALUE;
34+
// following loop checks
35+
// with all reachable points
36+
// and takes the minimum
37+
for(int j = i+1; j < n && j <= arr[i]+i; j++){
38+
if(min > jumps[i]){
39+
min = jumps[j];
40+
}
41+
}
42+
// Handle overflow
43+
if(min!=Integer.MAX_VALUE){
44+
jumps[i] = min+1;
45+
}else{
46+
jumps[i] = min; // or Integer.MAX_VALUE
47+
}
48+
}
49+
}
50+
System.out.println(jumps[0]);
51+
}
52+
53+
}

0 commit comments

Comments
 (0)