63. Largest sum of a run
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
numbers = [3, -4, 5, -1, 2, -6, 1]6Example 2
numbers = [-3, -1, -2]-1Example 3
numbers = [2, -1, 2]3Constraints
numbershas 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).
- For each item, think of the best run that ends exactly at it: it is either the item alone, or the item added to the best run ending just before it.
- That gives
run = max(x, run + x)for eachx. The answer is the biggestrunseen along the way. - Start both
runand the best answer atnumbers[0], not 0: with only negative numbers a start of 0 would wrongly win.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.