-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathJumpGameII.java
More file actions
36 lines (24 loc) · 686 Bytes
/
Copy pathJumpGameII.java
File metadata and controls
36 lines (24 loc) · 686 Bytes
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
package leetcode.medium;
public class JumpGameII {
int jump(int[] nums) {
int totalJumps = 0;
// destination is last index
int destination = nums.length - 1;
int coverage = 0, lastJumpIdx = 0;
// Base case
if (nums.length == 1) return 0;
// Greedy strategy: extend coverage as long as possible
for (int i = 0; i < nums.length; i++) {
coverage = Math.max(coverage, i + nums[i]);
if (i == lastJumpIdx) {
lastJumpIdx = coverage;
totalJumps++;
// check if we reached destination already
if (coverage >= destination) {
return totalJumps;
}
}
}
return totalJumps;
}
}