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 C# (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.Linq;

namespace _022_MaximumSumSequence
{
	class Program
	{
		static void Main ( string[] args )
		{
			while (true)
			{
				int dataCount = int.Parse (Console.ReadLine ());

				if (dataCount == 0)
				{
					break;
				}

				int inputItem = int.Parse (Console.ReadLine ());

				List<int> list = new List<int> (dataCount);
				int sign = 0;

				if (inputItem != 0)
				{
					list.Add (inputItem);
					sign = Math.Sign (list[0]);
				}

				int max = inputItem;

				for (int lp = 1; lp < dataCount; lp++)
				{
					inputItem = int.Parse (Console.ReadLine ());

					if (inputItem != 0)
					{
						int inputItemSign = Math.Sign (inputItem);

						if (sign == inputItemSign)
						{
							list[list.Count - 1] += inputItem;
						}
						else
						{
							list.Add (inputItem);
							sign = inputItemSign;
						}
					}

					if (max < inputItem)
					{
						max = inputItem;
					}
				}

				int sum = int.MinValue;
				int index = 0;

				if (0 < list.Count)
				{
					if (0 < list[0])
					{
						sum = list[0];
						index = 1;
					}
					else
					{
						if (2 <= list.Count)
						{
							sum = list[1];
							index = 2;
						}
					}

					if (list.Last () < 0)
					{
						list.RemoveAt (list.Count - 1);
					}
				}

				while (index < list.Count)
				{
					//- and +
					int add = list[index] + list[index + 1];
					if (0 < add)
					{
						sum += add;
					}
					else
					{
						if (max < sum)
						{
							max = sum;
						}

						sum = list[index + 1];
					}

					index += 2;
				}

				if (max < sum)
				{
					max = sum;
				}

				if (1 <= list.Count)
				{
					if (max < list.Last ())
					{
						max = list.Last ();
					}
				}

				Console.WriteLine (max);
			}
		}
	}
}