CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

Storm Harvester

Kadane's algorithm, O(n)

World 1 boss of Code the Hero, in Array Plains: scan, swap and sort a row of crates.

The idea

Kadane's algorithm keeps the best run ending at the current item. A run with a negative total never helps what comes next, so drop it.

The mission

The Storm Harvester mixed rotten crates (negative weights) into the row! We can take one run of neighbouring crates. Which run has the biggest total weight? At each crate: is it better to keep the current run going, or to start fresh here?

Goal: Find the largest total of any run of neighbouring crates (at least one crate) and submit it.

Boss: Storm Harvester. Hidden tests include rows that are all negative. Only one pass earns three stars.

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
crates.get(i)Lift crate i (may be negative)
Math.max(a, b)The bigger of two numbers
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 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. Levels open in order, so if this one is still locked you start at the first level that isn't.

More in Array Plains