Problem:
Score : 900 points

Problem Statement

Joisino has a formula consisting of N terms: A_1 op_1 A_2 ... op_{N-1} A_N.
Here, A_i is an integer, and op_i is an binary operator either + or -.
Because Joisino loves large numbers, she wants to maximize the evaluated value of the formula by inserting an arbitrary number of pairs of parentheses (possibly zero) into the formula.
Opening parentheses can only be inserted immediately before an integer, and closing parentheses can only be inserted immediately after an integer.
It is allowed to insert any number of parentheses at a position.
Your task is to write a program to find the maximum possible evaluated value of the formula after inserting an arbitrary number of pairs of parentheses.

Constraints

1≦N≦10^5

1≦A_i≦10^9

op_i is either + or -.

Input

The input is given from Standard Input in the following format:

N
A_1 op_1 A_2 ... op_{N-1} A_N

Output

Print the maximum possible evaluated value of the formula after inserting an arbitrary number of pairs of parentheses.

Sample Input 1

3
5 - 1 - 3

Sample Output 1

7

The maximum possible value is: 5 - (1 - 3) = 7.

Sample Input 2

5
1 - 2 + 3 - 4 + 5

Sample Output 2

5

The maximum possible value is: 1 - (2 + 3 - 4) + 5 = 5.

Sample Input 3

5
1 - 20 - 13 + 14 - 5

Sample Output 3

13

The maximum possible value is: 1 - (20 - (13 + 14) - 5) = 13.

Solution in C++ (GCC 5.4.1) (judge verdict: Accepted)

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int maxn = 1e5 + 5;

inline int gi()
{
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	int sum = 0;
	while ('0' <= c && c <= '9') sum = sum * 10 + c - 48, c = getchar();
	return sum;
}

inline int gc()
{
	char c = getchar();
	while (c != '-' && c != '+') c = getchar();
	return c == '+' ? 1 : -1;
}

inline void chkmax(ll &a, ll b) {if (a < b) a = b;}

int n, a[maxn], b[maxn], pw[3];
ll f[maxn][3];

int main()
{
	n = gi();
	a[1] = gi(); b[1] = 1;
	for (int i = 2; i <= n; ++i) b[i] = gc(), a[i] = gi();

	memset(f, -63, sizeof(f));
	f[1][0] = a[1];
	pw[0] = pw[2] = 1; pw[1] = -1;
	for (int i = 1; i <= n; ++i) {
		for (int j = 0; j <= 2; ++j)
			if (f[i][j] > -1e18) {
				chkmax(f[i + 1][j], f[i][j] + a[i + 1] * b[i + 1] * pw[j]);
				if (j) chkmax(f[i + 1][j - 1], f[i][j] + a[i + 1] * b[i + 1] * pw[j - 1]);
				if (b[i + 1] < 0 && j < 2) chkmax(f[i + 1][j + 1], f[i][j] + a[i + 1] * b[i + 1] * pw[j]);
				if (b[i + 1] < 0 && j) chkmax(f[i + 1][j], f[i][j] + a[i + 1] * b[i + 1] * pw[j - 1]);
			}
	}

	printf("%lld\n", max(f[n][0], max(f[n][1], f[n][2])));
	
	return 0;
}