#156Medium
Maximum subarray sum
Time: 1 s · Memory: 256 MB
- Prefix sums
Statement
You are given an array of integers. Find the maximum sum of a non-empty block of consecutive elements (a subarray).
Input format
The first line contains (). The second line contains integers ().
Output format
A single number — the maximum sum.
Examples
Input
8 -1 3 -2 5 3 -5 2 2
Output
9
Note
The sum of is . For every the best is the minimum of the earlier prefixes, so the answer is . This is one pass, (Kadane's algorithm is the same idea).
The subarray must be non-empty even when all numbers are negative: the answer is then the largest element, not . In the example . The sum reaches .
Source: CSES, problem 1643.
