Find the largest possible sum of a contiguous, non-empty run of numbers.
Input
Line 1: an integer n.
Line 2: n integers (which may be negative).
Output
The maximum sum over all contiguous non-empty subarrays.
Find the largest possible sum of a contiguous, non-empty run of numbers.
Line 1: an integer n.
Line 2: n integers (which may be negative).
The maximum sum over all contiguous non-empty subarrays.
Example 1
9 -2 1 -3 4 -1 2 1 -5 4
6
The run [4, -1, 2, 1] sums to 6, the maximum.
Example 2
1 5
5
A single element.
Example 3
4 -1 -2 -3 -4
-1
All negative — the best single element is -1.
A subarray either extends the best run ending at the previous element, or starts fresh at the current one.
Kadane's algorithm tracks the best sum ending here and the best seen overall in a single pass.
Kadane's algorithm: cur = max(x, cur + x) for each element; best = max(best, cur). Handles all-negative arrays because the run must be non-empty.
import sys
d = list(map(int, sys.stdin.read().split()))
n = d[0]
a = d[1:1 + n]
best = cur = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
print(best)
Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.