Arcade Tile Run

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

An arcade floor game is a strip of light-up tiles, each showing a score: bonuses like +4, traps like -5. You jump onto any tile, run forward one tile at a time, and jump off whenever you choose. Your score is the sum of the tiles you touched.

You can see every tile before you start. With the best place to jump on and off, what do you score?

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 at the 3 adds 3 - 5 = -2. Going 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 touch at least one. The best 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 end and add up the tiles between them. With running sums that is about n²/2 runs.

For 100,000 tiles that is around 5 billion runs. Two runs such as the one from tile 2 to tile 9 and the one from tile 3 to tile 9 share almost everything, yet each is computed from scratch.

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