CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

Container Dock

Two pointers, greedy O(n)

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

The idea

The shorter post limits the water, so any dock using it with a closer partner is worse. Discard it and move inward.

The mission

Two posts and the river between them make a dock. Water fills up to the shorter post. Water = shorter post × distance. Start with the widest dock: the two ends. Moving the taller post can never help. Always move the drone on the shorter post.

Goal: submit the most water any two posts can hold.

The commands you get

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

pip.read() / pix.read()Height of the post under each drone
pip.right() / pix.left()Move a drone inward
pip.index / pix.indexWhere each drone is
Math.min / Math.maxSmaller / bigger of two numbers
submit(value)Hand in the most water

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct on every test
  2. At most 2n reads
  3. At most n + 1 reads: read each post once

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