Arcade Tile Run

Easydynamic programmingAlso known as Maximum Subarray (Kadane's Algorithm)

An arcade has a floor game: a long strip of light-up tiles, each showing a score. Some scores are bonuses, like +4, and some are traps, like -5. You jump onto any tile you like, run forward across the tiles one by one, and jump off whenever you choose. Your score is the sum of every tile you touched.

You can see all the tiles before you start. If you pick the best place to jump on and off, what score do you get?

Your task

Write bestRun(tiles). Return the largest possible sum of a run of one or more consecutive tiles.

You must touch at least one tile, so if every tile is negative the answer is the least negative tile, not 0. Return only the score, not the positions.

bestRun(tiles: int[]) → int

Examples

Example 1
Input
tiles = [3, -5, 4, -1, 6, -8, 2]
Output
9
Why

Jump on at the 4 and off after the 6: 4 - 1 + 6 = 9. Starting earlier at the 3 adds 3 - 5 = -2, which only hurts. Running on past the 6 hits the -8, and the 2 after it does not make up for it.

Example 2
Input
tiles = [-4, -2, -7]
Output
-2
Why

Every tile is a trap, but you must land on at least one. The best you can do is the single tile -2.

Constraints

  • 1 ≤ tiles.length ≤ 100,000
  • -10,000 ≤ tiles[i] ≤ 10,000
Start with brute force

Try every start and every end, and add up the tiles between them. With running sums that is about n²/2 runs to check.

For 100,000 tiles that is around 5 billion runs. The waste is that the run from 2 to 9 and the run from 3 to 9 share almost everything, yet each is treated as a brand-new question.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code