A solar array logs the net energy gain (which may be negative on cloudy days) for each of n consecutive days. An operator wants the largest total that any single uninterrupted run of days could have produced.
Find the maximum sum over all non-empty contiguous runs of the sequence. If every day is a net loss, the answer is the single least-negative day (a run must contain at least one day). The intended approach splits the days in half and combines the best run in the left half, the best run in the right half, and the best run that straddles the midpoint.
Line 1: an integer n, the number of days.
Line 2: n space-separated integers, the daily net gains.
A single integer: the maximum contiguous run sum.
Example 1
Input
9 -2 1 -3 4 -1 2 1 -5 4
Expected
6
Explanation
The run 4, -1, 2, 1 sums to 6, which is the largest of any contiguous run.
Example 2
Input
3 -5 -2 -8
Expected
-2
Explanation
Every day is a loss, so the best single-day run is -2, the least negative value.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →