Home › Learn › World 1: Array Plains
FREEStorm 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.length | How 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
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct on every test
- At most 2n lifts
- 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.
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
- The Heaviest Crate: Linear scan, O(n)
- Reverse the Row: Two pointers, n/2 swaps
- Count the Apples: Counting in one pass, O(n)
- Irrigation Channels: Prefix sums: O(n) build, O(1) query
- Rotate the Row: Rotation by three reversals, O(n)
- Bubble Sort Machine: Sorting by adjacent swaps, O(n²)