Skip to content

Commit 5b92cbb

Browse files
Merge pull request #104 from aadityasinha-dotcom/min_Jumps
minimum jumps
2 parents 1379842 + 433ec6b commit 5b92cbb

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

GeeksForGeeks/minimum_Jumps.java

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

0 commit comments

Comments
 (0)