50 XP

63. Largest sum of a run

Intermediate dynamic programming lists

A run is one or more items that stand next to each other in a list. Write a function best_run(numbers) that takes a list of whole numbers and returns the largest total any run can have.

  • A run has at least one item, so when every number is negative the answer is the largest single number, not 0.
  • The run can be the whole list, or a single item.
  • A run may go through negative numbers when that pays: in [2, -1, 2] the best run is all three, totalling 3.

Trying every start and end point takes about n * n / 2 runs. There is a one-pass way: for each item, what is the best run that ends exactly there?

Example 1

Inputnumbers = [3, -4, 5, -1, 2, -6, 1]
Output6
ExplanationThe run 5, -1, 2 adds up to 6.

Example 2

Inputnumbers = [-3, -1, -2]
Output-1
ExplanationAll negative: the best run is just -1.

Example 3

Inputnumbers = [2, -1, 2]
Output3
ExplanationCrossing the -1 is worth it: 2 - 1 + 2.

Constraints

  • numbers has 1 to 200 whole numbers, each from -1000 to 1000.

Submit also runs 8 more tests you can't see.

Practises For Loops (lesson 13).

Code
def best_run(numbers):
    """Find the largest total of consecutive items.

    numbers: list of int, at least one
    Returns: int, the biggest sum of a run of one or more
        items in a row
    """
    # Write your code here
    pass