Skip to content

Commit fc12054

Browse files
committed
add: JumpToTheEnd
1 parent b0d5bc9 commit fc12054

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

java/Greedy/JumpToTheEnd.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
public class JumpToTheEnd {
2+
public boolean jumpToTheEnd(int[] nums) {
3+
// Set the initial destination to the last index in the array.
4+
int destination = nums.length - 1;
5+
// Traverse the array in reverse to see if the destination can be
6+
// reached by earlier indexes.
7+
for (int i = nums.length - 1; i >= 0; i--) {
8+
// If we can reach the destination from the current index,
9+
// set this index as the new destination.
10+
if (i + nums[i] >= destination) {
11+
destination = i;
12+
}
13+
}
14+
// If the destination is index 0, we can jump to the end from index
15+
// 0.
16+
return destination == 0;
17+
}
18+
}

0 commit comments

Comments
 (0)