Jump Game
Greedy: lesson 3 of 5
Carry one number: the furthest index still in reach.
Lesson 3 of 5 · 5 min
Jump Game
Step 1 of 9
Each cell says how far you may hop from it. The only question is whether the last index can be stood on.
The Idea
Each cell says how far you may jump from it, and you want to know whether the last cell is reachable at all.
You never need the route. Walk left to right carrying the furthest index you could get to; at each position, stretch that frontier with i + nums[i]. If a position sits past the frontier it can never be stepped on, so the answer is no. Reach the end and it is yes.
Real-World Example
A delivery drone hopping between rooftop pads, where each pad's battery allows a different maximum hop. Planning every route is wasted work — ground control only needs to know whether the far pad is inside the growing envelope of reachable pads.
The Code
def can_finish(nums):
reach = 0
for i, jump in enumerate(nums):
if i > reach: # this index was never reachable
return False
reach = max(reach, i + jump) # furthest index now in range
return True
print(can_finish([2, 3, 1, 1, 4])) # -> True
print(can_finish([3, 2, 1, 0, 4])) # -> FalseYour turn
Fill in the blank.
reach = ___(reach, i + jump)Mini quiz
1 / 3