livepython.net

222. Python Program to Find the Largest Sum of a Run of Numbers

HardPhase 3 · Challenge

This takes a few steps. You need split(), two for loops and a running total, and you know all of them. Work through a short list on paper first.

Overview

This is a famous interview question. A shop can use the same idea to find its best run of days.

Problem Statement

Pedro writes down how many coins a market stall wins or loses each day. A loss is a negative number. Pedro wants to find the best run of days.

A run is one number, or several numbers that sit next to each other in the list. The sum of a run is all its numbers added up. Find the largest sum of any run.

For example, in 3 -1 2 the runs are 3, -1, 2, 3 -1, -1 2 and 3 -1 2. Their sums are 3, -1, 2, 2, 1 and 4. So the largest sum is 4.

A run has at least one number. So when every number is negative, the answer is the biggest single number.

Print Largest sum: <sum>.

Examples

Example 1. Input -2 1 -3 4 -1 2 1 -5 4 gives:

Largest sum: 6

Why: the run 4 -1 2 1 adds up to 6. The -1 is worth keeping, because the 2 and 1 after it add more. No run has a bigger sum.

Example 2. Input -3 -1 -2 gives:

Largest sum: -1

Why: every number is negative, so each extra number makes the sum smaller. The best run is -1 alone.

Input

One line of whole numbers, with one space between them (1 number or more). The numbers can be negative. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Largest sum:, a space and the sum. The tests try 10 different inputs, also one number, zeros and lists where every number is negative.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Largest sum: 6

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.