Skip to content
CodeItRaw
Greedy & Intervals

Lesson 2/4

If from each box you can jump forward at most values[i], can you get to the end? You do not have to decide which box to jump to. Carry one number: the farthest box I can reach so far. If you can reach a box, you can reach every box before it too.

reach = 0
for i, jump in enumerate(values):
if i > reach:
return False
reach = max(reach, i + jump)
return True
At every box you ask first "could I get here?"; if not, everything after it is closed too. If you could, you update the farthest with the reach this box offers (i + jump).

The same idea meets you on a grid as the rule "go to the nearest target": collecting the nearest each time is usually a good plan and easy to work out. Mind the word "usually": nearest does not guarantee the shortest total way; with limited energy you have to measure it.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Nearest Chip

    Infiltration

  2. 02

    Jump Game

    Function

  3. 03

    Jump Game

    Code reading · Bug Hunt

If you would rather not wait for the order, every problem is open without locks: Problem list