-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem2.java
38 lines (31 loc) · 1.02 KB
/
Problem2.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
package Problems;
//Jump Game Problem (Array of integers given where each element represents the max number of steps that can be made forward from that element. Write a algorithm to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element.)
//Should be minimum jump in an array to reach the end of array.
public class Problem2 {
public static void main(String[] args) {
try {
int[] array = {4, 3, 2, 6, 2, 6, 1, 7, 8, 9, 3};
int jump = jumpGameProblem(array);
System.out.println(jump);
} catch(Exception e) {
System.out.println("Sorry, your array is empty!");
}
}
public static int jumpGameProblem(int[] array) {
int a = array[0], b = array[0];
int jump = 1;
for (int i = 1; i < array.length; i++) {
if (i == array.length - 1)
return jump;
a--;
b--;
if (array[i] > b)
b = array[i];
if (a == 0) {
jump++;
a = b;
}
}
return jump;
}
}