Problem:
Maximum Sum Sequence

Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence.

Input

The input consists of multiple datasets. Each data set consists of:

n
a1
a2
.
.
an

You can assume that 1 ≤ n ≤ 5000 and -100000 ≤ ai ≤ 100000.

The input end with a line consisting of a single 0.

Output

For each dataset, print the maximum sum in a line.

Sample Input

7
-5
-1
6
4
9
-6
-7
13
1
2
3
2
-2
-1
1
2
3
2
1
-2
1
3
1000
-200
201
0

Output for the Sample Input

19
14
1001

Solution in Python (judge verdict: Wrong Answer)

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)
from sys import stdin
from array import array

def grouping(nums):
    sign = None
    L = array(b'i')
    for s, n in ((i < 0, i) for i in nums):
        if sign is s:
            L[-1] += n
        else:
            sign = s
            L.append(n)

    if len(L) and L[-1] <= 0:
        del L[-1]
    return L

def collect(nl):
    result = 0
    while True:
        nl = grouping(nl)
        if len(nl) and nl[0] >= 0:
            result += nl.pop(0)
        if not len(nl):
            return result
        nl = array(b'i', (nl[i] + nl[i+1] for i in xrange(0, len(nl), 2)))

while True:
    n = int(stdin.readline())
    if not n:
        break

    L = array(b'i', (int(stdin.readline()) for _ in xrange(n)))
    val = max(L)
    if val <= 0:
        print(val)
        continue

    L = grouping(L)
    val = max(L)
    idx = L.index(val)

    Lprev = L[:idx]
    Lprev.reverse()
    Lnext = L[idx+1:]

    val += collect(Lprev) + collect(Lnext)
    print(val)