-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimum Jumps in geekfor geekss
50 lines (41 loc) · 1.66 KB
/
Minimum Jumps in geekfor geekss
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
Given an array arr[] of size n of non-negative integers. Each array element represents the maximum length of the jumps that can be made forward from that element. This means if arr[i] = x, then we can jump any distance y such that y ≤ x.
Find the minimum number of jumps to reach the end of the array starting from the first element. If an element is 0, then you cannot move through that element.
Note: Return -1 if you can't reach the end of the array.
Examples :
Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}, n = 11
Output: 3
Explanation:First jump from 1st element to 2nd element with value 3. From here we jump to 5th element with value 9, and from here we will jump to the last.
Input: arr = {1, 4, 3, 2, 6, 7}, n = 6
Output: 2
Explanation: First we jump from the 1st to 2nd element and then jump to the last element.
Input: arr = {0, 10, 20}, n = 3
Output: -1
Explanation: We cannot go anywhere from the 1st element.
Expected Time Complexity: O(n)
Expected Space Complexity: O(1)
solution:
class Solution {
static int minJumps(int[] arr, int n) {
int maxReach = 0,i;
int jump=0;
int lastIndex = 0;
if(n==1){
return 0;
}
for(i=0;i<n;i++){
maxReach = Math.max(maxReach,i+arr[i]);//it is giving every thing between the present to last
if(i == lastIndex){
if(maxReach ==i){
jump = -1;
break;
}
lastIndex = maxReach;
jump++;
if(maxReach >=n-1){
break;
}
}
}
return jump;
}
}