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.



Sample input:
3
5 - 1 - 3


Sample output:
7

Submission status: Wrong Answer

Solution code:
N = int(input())
M = list(input().split())
mini = 0
ans = 0
for s in M:
    if s == '-':
        mini += 1
    elif s == '+':
        pass
    else:
        s = int(s)
        if mini == 1:
            ans -= s
        else:
            ans += s
print(ans)

Submission status: Wrong Answer

Solution code:
input()
sm = de = 0
ans = 10 ** 15
for s in input().split('-'):
    a = list(map(int, s.split('+')))
    if sm:
        ans = min(ans, sum(a) + de)
        de += a[0]
    sm += sum(a)
print(sm - 2 * ans)

Submission status: Wrong Answer

Solution code:
n = input()
s = map(int, ('+ ' + raw_input()).replace('+ ', '+').replace('- ', '-').split())
s0 = [abs(x) for x in s]
for i in xrange(1, n):
	s0[i] += s0[i - 1]
loc = filter(lambda x: s[x] < 0, xrange(n)) + [n, n]
print max(sum(s), max([s0[n - 1] - (s0[loc[i + 1] - 1] - s0[loc[i] - 1]) * 2 for i in xrange(len(loc) - 1)]))

Submission status: Wrong Answer

Solution code:
n = input()
s = map(int, ('+ ' + raw_input()).replace('+ ', '+').replace('- ', '-').split())
s0 = [abs(x) for x in s]
for i in xrange(1, n):
	s0[i] += s0[i - 1]
loc = filter(lambda x: s[x] < 0, xrange(n))
print max(sum(s), max([s0[n - 1] - (s0[loc[i + 1] - 1] - s0[loc[i] - 1]) * 2 for i in xrange(len(loc) - 1)]))

Submission status: Wrong Answer

Solution code:
n = int(input())
ipt = input().split()
a = [int(ipt[i]) for i in range(0, 2*n,2)] + [0]
opr = [''] + [ipt[i] for i in range(1, 2*n-1, 2)] + ['-']
max_v = a[0]
for i in range(1,n):
    if opr[i] == '+':
        max_v += a[i]
    else:
        max_v -= a[i]
s = sum(a)
pre_minus = 0
total_pre_minus = 0
cur = 0
for i in range(1,n+1):
    if opr[i] == '-':
        if cur != 0:
            max_v = max(max_v, s-2*cur-total_pre_minus)
        cur = a[i]
        total_pre_minus += pre_minus
        pre_minus = a[i]
    else:
        if cur != 0:
            cur += a[i]
print(max_v)

Submission status: Wrong Answer

Solution code:
n = int(input())
ipt = input().split()
a = [int(ipt[i]) for i in range(0, 2*n,2)] + [0]
opr = [''] + [ipt[i] for i in range(1, 2*n-1, 2)] + ['-']
max_v = a[0]
for i in range(1,n):
    if opr[i] == '+':
        max_v += a[i]
    else:
        max_v -= a[i]
s = sum(a)
print(s)
pre_minus = 0
total_pre_minus = 0
cur = 0
for i in range(1,n+1):
    if opr[i] == '-':
        if cur != 0:
            max_v = max(max_v, s-2*cur-total_pre_minus)
        cur = a[i]
        total_pre_minus += pre_minus
        pre_minus = a[i]
    else:
        if cur != 0:
            cur += a[i]
print(max_v)

Submission status: Wrong Answer

Solution code:
n = int(input())
ipt = input().split()
a = [int(ipt[i]) for i in range(0, 2*n,2)] + [0]
opr = [''] + [ipt[i] for i in range(1, 2*n-1, 2)] + ['-']
max_v = a[0]
for i in range(1,n):
    if opr[i] == '+':
        max_v += a[i]
    else:
        max_v -= a[i]

s = sum(a)
cur = 0
for i in range(1,n+1):
    if opr[i] == '-':
        if cur != 0:
            max_v = max(max_v, s-2*cur)
        cur = a[i]
    else:
        if cur != 0:
            cur += a[i]
print(max_v)

Submission status: Wrong Answer

Solution code:
n = int(input())
ipt = input().split()
node = [int(ipt[0])]
plus = n-1
while plus > 0 and ipt[2*plus-1] == '+':
    node[0] += int(ipt[2*plus])
    plus -= 1
for i in range(plus):
    if ipt[2*i+1] == '+':
        node[-1] += int(ipt[2*i+2])
    else:
        node.append(int(ipt[2*i+2]))
if len(node) == 1:
    print(node[0])
else:
    print(sum(node) - 2*node[1])

Submission status: Wrong Answer

Solution code:
n = int(input())
ipt = input().split()
node = [int(ipt[0])]
plus = n-1
while plus > 0 and ipt[2*plus] == '+':
    node[0] += int(ipt[2*plus+1])
    plus -= 1
for i in range(plus):
    if ipt[2*i+1] == '+':
        node[-1] += int(ipt[2*i+2])
    else:
        node.append(int(ipt[2*i+2]))
if len(node) == 1:
    print(node[0])
else:
    print(sum(node) - 2*node[1])

Submission status: Wrong Answer

Solution code:
n = int(input())
ipt = input().split()
node = [int(ipt[0])]
for i in range(n-1):
    if ipt[2*i+1] == '+':
        node[-1] += int(ipt[2*i+2])
    else:
        node.append(int(ipt[2*i+2]))
if len(node) == 1:
    print(node[0])
else:
    print(sum(node) - 2*node[1])

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(raw_input())
a = deque(map(str, raw_input().split()))

m = int(a.popleft())
b = deque([])
while True:
    if len(a) == 0:
        b.append(m)
        break
    else:
        op = a.popleft()
        if op == '+':
            m += int(a.popleft())
        else:
            b.append(m)
            m = int(a.popleft())

if len(b) == 1:
    print b.popleft()
else:
    h = b.popleft() - b.popleft()
    print h + sum(b)

Submission status: Accepted

Solution code:
n = int(input())
a = input().split()
if(n==1):
    print(a[0])
    exit()

a_num = list( map(int, a[::2]))
a_op = a[1::2]

cumsum = a_num[::]
cumsum_op = [0] * n
cumsum_op[0] = a_num[0]
minus_ind = []
for i in range(1,n):
    cumsum[i] += cumsum[i-1]
    if(a_op[i-1] == '+'):
        cumsum_op[i] = cumsum_op[i-1] + a_num[i]
    else:
        cumsum_op[i] = cumsum_op[i-1] - a_num[i]
        minus_ind.append(i)

ans = cumsum_op[-1]
if(len(minus_ind)<2):
    print(ans)
    exit()

for l,r in zip(minus_ind[:-1],minus_ind[1:]):
    # lまでは符号通り、l,r-1までを減算、r以降を全て加算
    tmp = cumsum_op[l-1] - (cumsum[r-1] - cumsum[l-1]) + (cumsum[-1] - cumsum[r-1])
    ans = max(ans,tmp)

print(ans)

Submission status: Accepted

Solution code:

"""

https://atcoder.jp/contests/arc066/tasks/arc066_c

最終的な式における寄与を考える
-はどういう効果を持っている？

愚直な方法としてdpがある
dp[i][mnum] = i番目まで見て、-がmnum個重なってる状態での最大値
→ O(N^2)
じつは簡単にできる・保持しておくべき(答えになる)状態はもっと少ないのでは？
→これ、割と濃厚…か？

-の効果は、それ以降の寄与を反転させる
なるべく必要のない(無駄な)ところでは戻さない方が最適に近づく
現状 - で、足すやつを寄与+にしたい! → 戻す
現状 + で、足すやつを寄与-にしたい！→そんな場合はない
－直後のやつを寄与+にしたい！→ 戻せる+なら直前で-に戻せばいい

お？？？
A-B+C-D+E+F-…とやっていく
一度マイナスのカッコに入ると決めたとする
A-(B+C-(D+E+F)-G-(H+I))
すると、次の-以降はすべて+の寄与にできる

あとは耳dp！
dp[i][state] = i番目まで見て,stateの時の最大値
state = 0 #かっこをつけないで計算するモード
state = 1 #全引きモード
state = 2 #全足しモード

"""

N = int(input())

A = input().split()

dp = [int(A[0]),float("-inf"),float("-inf")]

for i in range(N-1):

    op = A[i*2+1]
    a =  int(A[i*2+2])

    ndp = [float("inf")] * 3

    if op == "+":

        ndp[0] = dp[0] + a
        ndp[1] = dp[1] - a
        ndp[2] = dp[2] + a

    else:

        ndp[0] = dp[0] - a
        ndp[1] = dp[0] - a
        ndp[2] = max(dp[2]+a ,dp[1]+a)

    dp = ndp

print (max(dp))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
terms = [[]] # マイナス区切り
op = '+'
for x in input().rstrip().split():
    if x in '+-':
        op = x
        continue
    x = int(x)
    if op == '+':
        terms[-1].append(x)
    else:
        terms.append([x])

# 何をマイナスにするか

min_minus = 10 ** 18
first_sum = 0
for t in terms[1:]:
    x = first_sum + sum(t)
    if x < min_minus:
        min_minus = x
    first_sum += t[0]

answer = sum(sum(t) for t in terms)
if len(terms) > 1:
    answer -= 2 * min_minus

print(answer)

Submission status: Accepted

Solution code:
def solve(n, inp):
    if n == 1:
        return int(inp[0])

    INF = -(10 ** 18)

    dp1, dp2, dp3 = int(inp[0]), INF, INF
    for op, a in zip(inp[1::2], inp[2::2]):
        a = int(a)
        if op == '+':
            dp1, dp2, dp3 = dp1 + a, max(dp2 - a, dp3 + a), dp3 + a
        else:
            dp1, dp2, dp3 = max(dp1 - a, dp2 + a), max(dp1 - a, dp2 + a), max(dp2 + a, dp3 - a)

    return dp1


n = int(input())
inp = input().split()
print(solve(n, inp))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3


def solve(n):

    s = input()
    sum_a = 0
    sum_n = 0
    sum_np = 0
    min_sum_np = 10 ** 15

    j = s.find('-')
    if j < 0:
        return sum(list(map(int, s.split(' + '))))

    sum_a = sum(list(map(int, s[:j - 1].split(' + '))))
    j += 2
    s += ' '
    len_s = len(s)
    sign = -1
    w = ''
    while j < len_s:
        ch = s[j]
        j += 1
        if ch == ' ':
            if len(w):
                a = int(w)
                sum_a += a
                w = ''
                if sign < 0:
                    sum_n += a
                    sum_np = 0
                else:
                    sum_np += a
        elif ch == '+':
            sign = 1
        elif ch == '-':
            min_sum_np = min(min_sum_np, sum_n + sum_np)
            sign = -1
        else:
            w += ch

    min_sum_np = min(min_sum_np, sum_n + sum_np)
    return sum_a - 2 * min_sum_np


def main():
    n = input()
    n = int(n)

    print(solve(n))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(str,input().split()))
dp = [[-float("inf")] *4 for i in range(n+1)]
dp[0][0] = 0
for i in range(len(a)):
    b = i//2+1
    if a[i] == "-":
        tmp = [-float("inf"),0,0,0]
        for j in range(3):
            tmp[j+1] = dp[b][j]
        dp[b] = tmp
        continue
    elif a[i] == "+":
        continue
    for j in range(4):
        for k in range(3):
            if j >= k:
                dp[b][k] = max(dp[b][k],dp[b-1][j]+((-1)**j)*int(a[i]))
print(dp[n][0])

Submission status: Accepted

Solution code:
input()
sm = de = 0
ans = 10 ** 15
for s in (input() + "-0").split('-'):
    a = list(map(int, s.split('+')))
    if sm:
        ans = min(ans, sum(a) + de)
        de += a[0]
    sm += sum(a)
print(sm - 2 * ans)

Submission status: Accepted

Solution code:
n = input()
s = map(int, ('+ ' + raw_input()).replace('+ ', '+').replace('- ', '-').split())
s0 = [abs(x) for x in s]
t = filter(lambda x: s[x + 1] < 0, xrange(n - 1)) + [n - 1] * 2
for i in xrange(1, n):
	s[i] += s[i - 1]
	s0[i] += s0[i - 1]
print max([s0[n - 1] - 2 * s0[t[i + 1]] + s0[t[i]] + s[t[i]] for i in xrange(len(t) - 1)])

Submission status: Accepted

Solution code:
n = input()
code = raw_input().split()
a = int(code[0]); b = c = -10**18
for op, v in zip(code[1::2], map(int,code[2::2])):
    if op is "+":
        b = max(b-v, c+v)
        c += v
        a = max(a+v, b)
    else:
        c = max(b+v, c-v)
        a = b = max(a-v, c)
print max(a, b, c)

Submission status: Accepted

Solution code:
n = input()
code = raw_input().split()
# DP(N, <parentheses nested>)
a = int(code[0]); b = c = -10**18
for op, v in zip(code[1::2], map(int,code[2::2])):
    if op is "+":
        d = max(b-v, c+v)
        a,b,c = max(a+v, d), d, c+v
    else:
        d = max(b+v, c-v)
        a,b,c = max(a-v, d), max(a-v, d), d
print max(a, b, c)

Submission status: Accepted

Solution code:
n = input()
code = raw_input().split()
# DP(N, <parentheses nested>)
dp = [[0]*3 for i in xrange(n)]
dp[0] = [int(code[0]), -10**18, -10**18]
for i in xrange(1,n):
    op, a = code[2*i-1: 2*i+1]
    v = int(a)
    if op is "+":
        dp[i][0] = max(dp[i-1][0]+v, dp[i-1][1]-v, dp[i-1][2]+v)
        dp[i][1] = max(              dp[i-1][1]-v, dp[i-1][2]+v)
        dp[i][2] =                                 dp[i-1][2]+v
    else:
        dp[i][0] = max(dp[i-1][0]-v, dp[i-1][1]+v, dp[i-1][2]-v)
        dp[i][1] = max(dp[i-1][0]-v, dp[i-1][1]+v, dp[i-1][2]-v)
        dp[i][2] = max(              dp[i-1][1]+v, dp[i-1][2]-v)
print max(dp[-1])

Submission status: Runtime Error

Solution code:
#include<bits/stdc++.h>
//using namespace std;
#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define rep(i,j,n) for(ll i=(ll)(j);i<(ll)(n);i++)
#define REP(i,j,n) for(ll i=(ll)(j);i<=(ll)(n);i++)
#define per(i,j,n) for(ll i=(ll)(j);(ll)(n)<=i;i--)
#define ll long long
#define ALL(a) (a).begin(),(a).end()
#define disup(A,key) distance(A.begin(),upper_bound(ALL(A),(ll)(key)))
#define dislow(A,key) distance(A.begin(),lower_bound(ALL(A),(ll)(key)))
#define pb emplace_back
#define mp std::make_pair
//
#define endl "\n"
//using std::endl;
using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::upper_bound;
using std::lower_bound;
using vi=vector<ll>;
using vii=vector<vi>;
using pii=std::pair<ll,ll>;
//
constexpr ll MOD=1e9+7;
//constexpr ll MOD=998244353; 
//constexpr ll MOD=10000000;
//constexpr ll MOD=1e4;
//constexpr ll MOD=1e5;
constexpr ll MAX=3e6;
constexpr ll inf=(1ll<<60);
template<class T>
class prique :public std::priority_queue<T, std::vector<T>, std::greater<T>> {};
template<typename T>
struct Segment_tree{
    ll N;
    T mem;
    vector<T> node;
    Segment_tree(vector<T> &X,T m):mem(m){
        ll sz=X.size();
        N=1;
        while(N<sz) N*=2;
        node.resize(2*N-1,mem);
        rep(i,0,sz) node[N-1+i]=X[i];
        per(i,N-2,0){
            node[i]=Compare(node[i*2+1],node[i*2+2]);
        }
    }
    T Compare(T &A,T &B){
        return std::max(A,B);
    }
    void update(ll X,T val){
        X+=N-1;
        node[X]=val;
        while(X>0){
            X=(X-1)/2;
            node[X]=Compare(node[X*2+1],node[X*2+2]);
        }
    }
    T Query(ll a,ll b,ll now,ll l,ll r){ //[a,b),[l,r)
        if(r<0) r=N;
        if(r<=a||b<=l) return mem;
        if(a<=l&&r<=b) return node[now];
        auto vl=Query(a,b,now*2+1,l,(l+r)/2),vr=Query(a,b,now*2+2,(l+r)/2,r);
        return Compare(vl,vr);
    }
};
template<typename T>
struct lazy_Segment_tree{
    int N;
    vector<T> node,lazy;
    T INF;
    lazy_Segment_tree(vector<T> X,T Y):INF(Y){
        N=1;
        while(X.size()>N) N*=2;
        node.resize(2*N-1,Y);
        lazy.resize(2*N-1);
        rep(i,0,X.size()) node[i+N-1]=X[i];
        per(i,N-2,0) node[i]=compare(node[i*2+1],node[i*2+2]);
    }
    T compare(T X,T Y){
        return std::max(X,Y);
    }
    T plus(T X,int l,int r){
        return X;
    }
    void eval(int now,int l,int r){
        if(lazy[now]==0) return;
        node[now]+=lazy[now];
        if(r-l>1){
            lazy[now*2+1]+=plus(lazy[now],l,r);
            lazy[now*2+2]+=plus(lazy[now],l,r);
        }
        lazy[now]=0;
    }
    void update(int a,int b,T add,int now=0,int l=0,int r=-1){
        if(r<0) r=N;
        eval(now,l,r);
        if(b<=l||r<=a) return;
        if(a<=l&&r<=b){
            lazy[now]+=add;
            eval(now,l,r);
        }
        else{
            update(a,b,add,now*2+1,l,(r+l)/2);
            update(a,b,add,now*2+2,(r+l)/2,r);
            node[now]=compare(node[now*2+1],node[now*2+2]);
        }
    }
    T Query(int a,int b,int now=0,int l=0,int r=-1){
        if(r<0) r=N;
        eval(now,l,r);
        if(b<=l||r<=a) return INF;
        if(a<=l&&r<=b) return node[now];
        return compare(Query(a,b,now*2+1,l,(r+l)/2),Query(a,b,now*2+2,(r+l)/2,r));
    }
};
struct Tree{
    int N;
    vii dp;
    vi dist;
    Tree(vii edge){
        N=edge.size();
        dp.resize(N);
        dist.resize(N,-1);
        for(int i=0;i<N;i++) dp[i].resize(30);
        dist[0]=dp[0][0]=0;
        std::queue<int> que;
        que.push(0);
        while(!que.empty()){
            int now=que.front(); que.pop();
            for(int i=0;i<edge[now].size();i++){
                int next=edge[now][i];
                if(dist[next]==-1){
                    dist[next]=dist[now]+1;
                    que.push(next);
                    dp[next][0]=now;
                }
            }
        }
        for(int i=1;i<30;i++){
            for(int j=0;j<N;j++) dp[j][i]=dp[dp[j][i-1]][i-1];
        }
    }
    int LCA(int X,int Y){
        if(dist[X]<dist[Y]) std::swap(X,Y);
        {
            int Z=dist[X]-dist[Y];
            for(int i=0;i<30;i++){
                if(Z&(1<<i)){
                    X=dp[X][i];
                }
            }
        }
        if(X==Y) return X;
        for(int i=29;i>=0;i--){
            if(dp[X][i]!=dp[Y][i]){
                X=dp[X][i];
                Y=dp[Y][i];
            }
        }
        return dp[X][0];
    }
};
struct Binary_indexed_tree{
    int N;
    vi bit;
    Binary_indexed_tree(int n):N(n){
        bit.resize(N+1,0);
    }
    void add(int x,ll a){
        for(x;x<=N;x+=(x&-x)) bit[x]+=a;
    }
    ll sum(int x){
        ll ret=0;
        for(x;x>0;x-=(x&-x)) ret+=bit[x];
        return ret;
    }
    ll lower_bound(ll X){
        if(sum(N)<X) return -1;
        ll ret=0,memo=1,sum=0;
        while(memo*2<=N) memo*=2;
        while(memo>0){
            if(memo+ret<=N&&sum+bit[memo+ret]<X){
                sum+=bit[memo+ret];
                ret+=memo;
            }
            memo/=2;
        }
        return ret+1;
    }
};
struct Union_Find{
    ll N;
    vi par;
    vi siz;
    Union_Find(int n):N(n){
        par.resize(N);
        siz.resize(N,1);
        rep(i,0,N) par[i]=i;
    }
    ll root(ll X){
        if(par[X]==X) return X;
        return par[X]=root(par[X]);
    }
    bool same(ll X,ll Y){
        return root(X)==root(Y);
    }
    void unite(ll X,ll Y){
        X=root(X);
        Y=root(Y);
        if(X==Y) return;
        par[X]=Y;
        siz[Y]+=siz[X];
        siz[X]=0;
    }
    ll size(ll X){
        return siz[root(X)];
    }
};
long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}
vi fac,finv,inv;
void COMinit() {
    fac.resize(MAX);
    finv.resize(MAX);
    inv.resize(MAX);
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}
ll COM(ll n,ll r){
    if(n<r||n<0||r<0) return 0;
    return fac[n]*finv[r]%MOD*finv[n-r]%MOD;
}
void comp(vi &A){
    std::map<ll,ll> memo;
    rep(i,0,A.size()) memo[A[i]]=0;
    ll cnt=1;
    for(auto &p:memo) p.second=cnt++;
    rep(i,0,A.size()) A[i]=memo[A[i]];
}
void dec(std::map<ll,ll> &mem,ll X){
    mem[X]--;
    if(mem[X]==0) mem.erase(X);
}
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    ll N; cin>>N;
    vi A(N);
    vector<char> op(N);
    rep(i,0,N-1) cin>>A[i]>>op[i];
    cin>>A[N-1];
    vii dp(N,vi(3,-inf));
    dp[0][0]=A[0];
    rep(i,1,N){
        if(op[i-1]=='+'){
            dp[i][0]=std::max({dp[i-1][0],dp[i-1][1],dp[i-1][2]})+A[i];
            dp[i][1]=dp[i-1][1]-A[i];
            dp[i][2]=dp[i-1][2]+A[i];
        }
        else{
            dp[i][0]=dp[i-1][0]-A[i];
            dp[i][1]=std::max(dp[i-1][0]-A[i],dp[i-1][1]+A[i]);
            dp[i][2]=std::max(dp[i-1][2]+A[i],dp[i-1][1]+A[i]);
        }
    }
    ll ans=-inf;
    rep(i,0,3) ans=std::max(ans,dp[N-1][i]);
    cout<<ans<<endl;
}

Submission status: Runtime Error

Solution code:
N = int(input())
M = list(input().split())
mini = 0
ans = 0
for s in M:
    if s == '-':
        mini += 1
    elif s == '+':
        pass
    else:
        s = int(s)
        if mini == 1:
            ans -= s
        else:
            ans += s
print(max(ans,eval(''.join(M))))

Submission status: Runtime Error

Solution code:
n = int(input())
ipt = input().split()
a = [int(ipt[i]) for i in range(0, 2*n+1,2)] + [0]
opr = [''] + [ipt[i] for i in range(1, 2*n, 2)] + ['-']
max_v = a[0]
for i in range(1,n):
    if opr[i] == '+':
        max_v += a[i]
    else:
        max_v -= a[i]

s = sum(a)
cur = 0
for i in range(1,n+1):
    if opr[i] == '-':
        if cur != 0:
            max_v = max(max_v, s-2*cur)
        cur = a[i]
    else:
        if cur != 0:
            cur += a[i]
print(max_v)

Submission status: Runtime Error

Solution code:
n = int(input())
ipt = input().split()
node = [int(ipt[0])]
plus = n
while plus > 1 and ipt[2*plus-1] == '+':
    node[0] += int(ipt[2*plus])
    plus -= 1
for i in range(plus):
    if ipt[2*i+1] == '+':
        node[-1] += int(ipt[2*i+2])
    else:
        node.append(int(ipt[2*i+2]))
if len(node) == 1:
    print(node[0])
else:
    print(sum(node) - 2*node[1])

Submission status: Runtime Error

Solution code:
import sys

n = int(next(sys.stdin).strip())
items = next(sys.stdin).strip().split()

cache = {(i, i + 1): (int(items[2 * i]), int(items[2 * i])) for i in range(n)}


def value(l, r):
    if (l, r) in cache:
        return cache[(l, r)]

    lower, upper = float('inf'), float('-inf')
    for c in range(l + 1, r):
        ll, lu = value(l, c)
        rl, ru = value(c, r)
        op = items[2 * c - 1]
        if op == '+':
            lower = min(lower, ll + rl)
            upper = max(upper, lu + ru)
        elif op == '-':
            lower = min(lower, ll - ru)
            upper = max(upper, lu - rl)

    cache[(l, r)] = (lower, upper)
    return lower, upper

lower, upper = value(0, n)
print(upper)

Submission status: Runtime Error

Solution code:
import sys

n = int(next(sys.stdin).strip())
items = next(sys.stdin).strip().split()

cache = {(i, i + 1): (int(items[2 * i]), int(items[2 * i])) for i in range(n)}


def value(l, r):
    if (l, r) in cache:
        return cache[(l, r)]

    lower, upper = float('inf'), float('-inf')
    for c in range(l + 1, r):
        ll, lu = value(l, c)
        rl, ru = value(c, r)
        op = items[2 * c - 1]
        if op == '+':
            lower = min(lower, ll + rl)
            upper = max(upper, lu + ru)
        elif op == '-':
            lower = min(lower, ll - ru)
            upper = max(upper, lu - rl)

    return lower, upper

lower, upper = value(0, n)
print(upper)