π§ Problem Overview
Youβre given an integer array nums, where each element represents the maximum jump length from that position. Starting at index 0, determine if you can reach the last index.
Example 1
Input: [2, 3, 1, 1, 4]
Output: true
Explanation: 0 β 1 β 4
Example 2
Input: [3, 2, 1, 0, 4]
Output: false
Explanation: Stuck at index 3, canβt jump to 4.
βοΈ Method 1: Greedy
π§© Intuition
We only care about the farthest index we can reach at each step.
If at any index i, we find that i is beyond the farthest reachable index so far, it means weβre stuck and cannot proceed.
So we maintain a variable rightmost β the farthest index we can reach as we iterate through the array.
For each index i:
If i <= rightmost, we can reach it.
Update rightmost = max(rightmost, i + nums[i]).
If rightmost reaches or exceeds the last index, return True.
Otherwise, after the loop, if rightmost < last index, return False.
π Walkthrough Examples
β Example 1:
[2, 3, 1, 1, 4]
Start at index 0 β rightmost = max(0, 0 + 2) = 2
Index 1 is within reach β rightmost = max(2, 1 + 3) = 4
4 β₯ last index β return True
β Example 2:
[3, 2, 1, 0, 4]
Start at index 0 β rightmost = 3
Index 1, 2, 3 are all β€ 3, but no further jump improves rightmost
Index 4 > rightmost, unreachable β return False
π§βπ» Code (Java)
public class Solution {
public boolean canJump(int[] nums) {
int rightmost = 0;
for (int i = 0; i < nums.length; ++i) {
if (i <= rightmost) {
rightmost = Math.max(rightmost, i + nums[i]);
if (rightmost >= nums.length - 1) {
return true;
}
}
}
return false;
}
}
β±οΈ Complexity Analysis
Time Complexity: O(n) β We scan the array once.
Space Complexity: O(1) β No extra space used.