Introduction
Jump Game is one of the most popular Greedy problems.
You are given:
- An array nums
- nums[i] represents the maximum jump length from index i
Goal:
Determine whether you can reach the last index.
Example
Input
nums = [2,3,1,1,4]Output
trueExplanation
Start at index 0Jump to index 1
Jump to index 4
Reached the end.
Key Observation
Track the farthest position reachable so far.
If the current index becomes greater than the farthest reachable position, reaching the end is impossible.
Algorithm
- Initialize farthest = 0.
- Traverse the array.
- If current index > farthest:
- Return false.
- Update farthest reachable position.
- If farthest reaches last index:
- Return true.
- Continue traversal.
Dry Run
Input
nums = [2,3,1,1,4]Index 0
farthest = max(0, 0+2)farthest = 2Index 1
farthest = max(2, 1+3)farthest = 4Index 2
Last index reachedIndex 4
Last index reachedAnswer
true Approach : Greedy
Always keep track of the maximum index reachable at any point.
If we can continuously extend our reachable range to include the last index, the answer is true.