Maximum Sum of Non-Overlapping SubsegmentsMedium

Maximum Sum of Non-Overlapping Subsegments

MediumPractice library · +20 XPdynamic programminggreedy

Given an array of N integers, find the maximum possible sum of a set of non-overlapping subsegments. You can choose to select zero subsegments, in which case the sum is 0. A subsegment is defined by its start and end indices (inclusive). Two subsegments are non-overlapping if they do not share any common elements.

Input

The first line contains an integer N. The second line contains N space-separated integers, the elements of the array.

Output

Print a single integer, the maximum possible sum of non-overlapping subsegments.

Constraints

1 <= N <= 200000, -10^9 <= a_i <= 10^9

Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
9
1 -2 3 4 -1 2 1 -5 4
Output
15

The optimal set of segments are [1], [3,4], [2,1], [4] with total sum 1 + 7 + 3 + 4 = 15.

Example 2

Input
3
-1 -2 -3
Output
0

Since all numbers are negative, the maximum sum is 0 by selecting no segments.

Hints