Python coding

Largest run sum

A run is one or more consecutive values of nums. Return the largest sum that any run can have.

nums has 1 to 10,000 integers between −10,000 and 10,000. Aim for one pass and O(1) extra space.

Besides the tests, one large input (6,000 values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • largest_run_sum([2,-3,4,-1,2,-5,3]) → 5
  • largest_run_sum([6,-2,7]) → 11
  • largest_run_sum([5,-9,5]) → 5
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Scan left to right carrying the best total of a run that ends at the current value. What should happen to that total before you add the next value?

Hint 2

A negative carried total only lowers whatever follows, so drop it: current = max(current, 0) + x. The answer is the largest current you see.

Hint 3

Don't start best at 0: when every value is negative, the best run is the largest single value, and 0 is no run at all. Start from nums[0].

Solution and why it works
pythonO(n) · O(1)
def largest_run_sum(nums: list[int]) -> int:
    best, current = nums[0], 0           # current: best total of a run ending at the value just read
    for x in nums:
        current = max(current, 0) + x    # a negative carried total only lowers x: start over at x
        best = max(best, current)
    return best

The greedy choice at each value: extend the run that ends just before it, or start fresh. Extending helps exactly when that carried total is positive, so a negative prefix is dropped for good: any run that continues past it is better without it (exchange argument). One pass and one running total: O(n) time and O(1) space, where summing every start and end is O(n²). The trap is the empty run: starting best at 0 returns 0 for [-4, -2, -7], whose answer is -2.