Skip to Content

Best stretch

Level B. Teaches a linear scan checked against a brute force.

You are given n integers (1 ≤ n ≤ 2·10⁵, each between −10⁹ and 10⁹). Print the largest sum of a non-empty run of consecutive elements.

Input: n, then the n integers. Output: one number.

InputOutput
5
-1 3 -2 4 -9
5
5 tests · Ctrl+Enter
Hints
  • cur is the best sum of a run that ends at the current element: either extend the previous run or start again here.
  • To check a scan like this, add the obvious O(n²) answer to the same file as @alt(program) and press Stress in the playground. With small ranges for n and a, it compares the two on random inputs and shrinks any disagreement. Chapter 11 shows how.
  • With all values negative, the answer is the largest single value, which is why best starts at a[0], not 0.
  • Greedy and two pointers has other one-pass scans; Stress and trace shows the stress workflow step by step.