Given an array where each element represents your maximum jump length from that position, determine whether you can reach the last index starting from the first.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array where each element represents your maximum jump length from that position, determine whether you can reach the last index starting from the first.
The first genuinely greedy array problem in this course — instead of simulating every possible sequence of jumps, it's solved by tracking a single running value: the farthest index reachable so far.
Whenever a problem asks whether some goal is reachable through a sequence of choices, and each choice's effect is a simple numeric bound like a jump length, check whether tracking the single best reachable bound so far — rather than exploring every path — is enough.
Track one running value, farthest, the largest index reachable using jumps from any position visited so far. Scan the array left to right: at each index i, if i is already beyond farthest, that index (and everything after it) is unreachable, so the answer is false. Otherwise, update farthest to max(farthest, i + nums[i]). If farthest ever reaches or exceeds the last index, the array is fully reachable and the answer is true. This greedy update is always safe because reaching a farther index can never hurt — every position reachable from a closer index is also reachable from (or before) a farther one.
class Solution {
public boolean canJump(int[] nums) {
int farthest = 0;
for (int i = 0; i < nums.length; i++) {
if (i > farthest) {
return false;
}
farthest = Math.max(farthest, i + nums[i]);
}
return true;
}
}