Skip to content
CodeItRaw
Greedy & Intervals

Lesson 3/4

What is the fewest jumps to the end? Again you pick no box; this time you think in layers. Walk all the boxes one jump can reach and find the farthest point reachable from them: that is the edge of the layer two jumps reach. When you arrive at an edge, count one jump.

jumps = edge = farthest = 0
for i in range(len(values) - 1):
farthest = max(farthest, i + values[i])
if i == edge:
jumps += 1
edge = farthest
return jumps
edge is the last box reachable with the current number of jumps. Until you get to it you gather "how far could the next jump take me at most"; you never decide which box to jump from. The loop does not enter the last box: there is no need to jump from there.

For gas stations on a circle another greedy idea works: if you set out from some start and the tank goes negative at some point, then no station in that stretch is a good start (you reached each with at least zero fuel and it still was not enough). You start over from the next station and never try any start twice.

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

    Fewest Jumps

    Function

  2. 02

    Gas Station

    Function

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