forked from bediacademy/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin_jump
66 lines (38 loc) · 712 Bytes
/
min_jump
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
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;
int max(int x, int y)
{
return (x > y) ? x : y;
}
int minJumps(int arr[], int n)
{
if (n <= 1)
return 0;
if (arr[0] == 0)
return -1;
int maxReach = arr[0];
int step = arr[0];
int jump = 1;
int i = 1;
for (i = 1; i < n; i++) {
if (i == n - 1)
return jump;
maxReach = max(maxReach, i + arr[i]);
step--;
if (step == 0) {
jump++;
if (i >= maxReach)
return -1;
step = maxReach - i;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 3, 5, 8, 8, 2, 6, 7, 6, 8, 9 };
int size = sizeof(arr) / sizeof(int);
cout << ("Minimum number of jumps to reach end is %d ",
minJumps(arr, size));
return 0;
}