CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

The Heaviest Crate

Linear scan, O(n)

Level 1.1 of Code the Hero, in Array Plains: scan, swap and sort a row of crates.

The idea

Walk the row once, remembering the best value so far. Every item must be looked at once, so no method can beat one pass.

The mission

King Brute scrambled my crates! I need the heaviest one for the harvest cart. Write code to walk the row. crates.get(i) makes our hero lift crate i and tell you its weight. Every lift takes time. A good farmer lifts each crate only once.

Goal: Find the weight of the heaviest crate and hand it in with submit(weight).

The commands you get

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

crates.lengthHow many crates are in the row
crates.get(i)Hero walks to crate i, lifts it and returns its weight
submit(value)Hand in your answer. This ends the run
hero.say(text)Make the hero speak
console.log(x)Print to the Log tab

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct answer on every test
  2. At most 2n lifts
  3. At most n lifts: one pass

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. It runs in your browser, on a phone or a laptop.

More in Array Plains