Under construction

Still being built. Things may change

Sum Over Zero

Interview

Time limit1sMemory limit1024 MB

Summary
Choose pairwise disjoint segments whose element sums are all non-negative, maximizing the total length of the chosen segments.
Level

Medium6 of 10

Topics
Dynamic programming, Prefix sum, Sorting
Solved
No attempts yet

Problem

You are given an array a1,a2,…,ana_1, a_2, \ldots, a_n of nn integers. Let SS be a set of segments that satisfies the following conditions.

  • Each element of SS has the form [x,y][x, y], where xx and yy are integers between 11 and nn, inclusive, and x≤yx \leq y.
  • No two segments in SS intersect. Two segments [a,b][a, b] and [c,d][c, d] intersect if and only if there exists an integer xx such that a≤x≤ba \leq x \leq b and c≤x≤dc \leq x \leq d.
  • For each [x,y][x, y] in SS, ax+ax+1+…+ay≥0a_x + a_{x+1} + \ldots + a_y \geq 0.

The length of a segment [x,y][x, y] is y−x+1y - x + 1. f(S)f(S) is the sum of the lengths of every segment in SS, so f(S)=∑[x,y]∈S(y−x+1)f(S) = \sum_{[x, y] \in S} (y - x + 1). If SS is empty, f(S)f(S) is 00.

Find the maximum f(S)f(S) over all possible SS.

Input

The first line contains one integer nn (1≤n≤2⋅1051 \leq n \leq 2 \cdot 10^5).

The next line contains nn integers a1,a2,…,ana_1, a_2, \ldots, a_n (−109≤ai≤109-10^9 \leq a_i \leq 10^9).

Output

Print a single integer, the maximum f(S)f(S).

Examples3

  1. Example 1

    Input
    5
    3 -3 -2 5 -4
    
    Expected output
    4
    
  2. Example 2

    Input
    10
    5 -2 -4 -6 2 3 -6 5 3 -2
    
    Expected output
    9
    
  3. Example 3

    Input
    4
    -1 -2 -3 -4
    
    Expected output
    0