CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

The Sliding Net

Sliding window, O(n)

Level 2.4 of Code the Hero, in Twin Rivers: two pointers and sliding windows.

The idea

A fixed-size window keeps a running total; each slide costs one add and one subtract instead of k additions.

The mission

The fishing net covers k barrels at once. Which k neighbours are heaviest together? Lazy way: re-add every barrel in the net at each position. Slow! Clever way: when the net slides, add the barrel that enters and subtract the one that leaves.

Goal: Find the biggest total weight of any net.size neighbouring barrels and submit(best).

The commands you get

You write real Python, Java or JavaScript. These are the moves the hero understands in this level:

crates.get(i)Hero reads barrel i
crates.lengthNumber of barrels
net.sizeHow many barrels the net covers (k)
net.slide()Slide the net one barrel right
net.startFirst barrel under the net
submit(value)Hand in the best total

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct on every test
  2. At most k × (n − k + 1) reads
  3. At most k + 2 × (n − k) reads: true sliding

Your code is also checked on hidden inputs, so it has to work for any case, not only the one on screen.

▶ Play this level free

No sign-up. Levels open in order, so if this one is still locked you start at the first level that isn't.

More in Twin Rivers