Problem:
 Score : 500 points    Problem Statement "Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.  Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i -th sushi is placed, is x_i meters. Also, the i -th sushi has a nutritive value of v_i kilocalories.  Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.  Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.      Constraints  1 ≤ N ≤ 10^5  2 ≤ C ≤ 10^{14}  1 ≤ x_1 < x_2 < ... < x_N < C  1 ≤ v_i ≤ 10^9  All values in input are integers.       Subscores  300 points will be awarded for passing the test set satisfying N ≤ 100 .         Input Input is given from Standard Input in the following format:  N  C  x_1  v_1  x_2  v_2  :  x_N  v_N       Output If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c .        Sample Input 1 3 20
2 80
9 120
16 1      Sample Output 1 191  There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.       Sample Input 2 3 20
2 80
9 1
16 120      Sample Output 2 192  The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.       Sample Input 3 1 100000000000000
50000000000000 1      Sample Output 3 0  Even though the only sushi is so far that it does not fit into a 32 -bit integer, its nutritive value is low, thus he should immediately leave without doing anything.       Sample Input 4 15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000      Sample Output 4 6500000000  All these sample inputs above are included in the test set for the partial score.

Solution (Python):
N, C = map(int, input().split())
XV = [[int(x) for x in input().split()] for _ in range(N)]

XV.sort()

def g():
    t_n = [(0, 0)] * (N + 1)
    ans = 0
    score = 0
    pos = 0
    for i, (x, v) in enumerate(XV, 1):
        score += v - (x - pos)
        pos = x
        ans = max(ans, score)
        t_n[i] = (pos, ans)
    
    t_r = [(0, 0)] * (N + 1)
    ans = 0
    score = 0
    pos = C
    for i, (x, v) in enumerate(reversed(XV), 1):
        score += v - (pos - x)
        pos = x
        ans = max(ans, score)
        t_r[i] = (pos, ans)
    
    ans = 0
    for i in range(1, N+1):
        ans = max(
                ans,
                t_n[i][1],
                t_r[i][1],
                t_n[i][1] -      t_n[i][0]  + t_r[N - i][1],
                t_r[i][1] - (C - t_r[i][0]) + t_n[N - i][1],
                )

    return ans

print(g())

Solution (Python):
N, C = map( int, input().split())
S = [ list( map( int, input().split())) for _ in range(N)]
X = [0]*(N+1)
RX = [0]*(N+1)
CX = [-C]*(N+1)
RCX = [-C]*(N+1)
now = 0
M = -C
m = -C
for i in range(N):
    X[i+1] = X[i] + S[i][1] - S[i][0] + now
    now = S[i][0]
    M = max(M, X[i+1])
    CX[i+1] = M
now = 0
for i in range(N):
    x, v = S[-i-1]
    x = C - x
    RX[i+1] = RX[i] + v - x + now
    now = x
    m = max(m, RX[i+1])
    RCX[i+1] = m
ans = 0
CX[0] = 0
RCX[0] = 0
RS = S[::-1]
S.insert(0,[0,0])
RS.insert(0,[C,0])

for i in range(N+1):
    ans = max( ans, X[i] + max(RCX[N-i] - S[i][0], 0))
    ans = max( ans, RX[i] + max(CX[N-i] - (C - RS[i][0]),0))
print(ans)

Solution (Python):
n,c=map(int,input().split())


kyori=[0]*(n+2)
kyori[n+1]=c
calo=[0]*(n+2)
ans=[0]
tmp=0

for i in range(1,n+1):
    x,v=map(int,input().split())
    kyori[i]=x
    calo[i]=v
    tmp+=v-(x-kyori[i-1])
    ans.append(tmp)


tmp=0
for i in range(n):
    tmp+=calo[-2-i] - (kyori[-1-i]-kyori[-2-i])
    ans.append(tmp)


i=1
rmax=0
tmpmax=0
tmp=0
while(2*kyori[i]< c and i<=n):
    tmp+=calo[i]-2*(kyori[i] -kyori[i-1])
    if(tmpmax<tmp):
        tmpmax=tmp
        rmax=i
    i+=1


tmp=0
tmpmax_max=0
i=0
while(rmax < -i+n):
    tmp+=calo[-2-i] - (kyori[-1-i] - kyori[-2-i])
    if(tmpmax_max<tmp):
        tmpmax_max=tmp
    i+=1
ans.append(tmpmax+ tmpmax_max)


now=tmpmax+ tmp
for i in range(rmax):
    tmpmax+= -calo[rmax-i]+2*(kyori[rmax-i] - kyori[rmax-i-1])
    tmp+=calo[rmax-i] -(kyori[rmax+1-i]-kyori[rmax-i])
    if(tmpmax_max<tmp):
        tmpmax_max=tmp
    ans.append(tmpmax+tmpmax_max)




i=0
lmax=0
tmpmax=0
tmp=0
while(2*kyori[-2-i] > c and i<n):
    tmp+=calo[-2-i]-2*(kyori[-1-i] -kyori[-2-i])
    if(tmpmax<tmp):
        tmpmax=tmp
        lmax=-i+n
    i+=1
if(lmax==0):
    lmax=n+1
tmp=0
tmpmax_max=0
i=1
while(i < lmax):
    tmp+=calo[i] - (kyori[i] - kyori[i-1])
    if(tmpmax_max <tmp):
        tmpmax_max=tmp
    i+=1

ans.append(tmpmax+ tmpmax_max)



now=tmpmax+ tmp
for i in range(n-lmax):
    tmpmax+= -calo[lmax+i]+2*(kyori[lmax+i+1] - kyori[lmax+i])
    tmp+=calo[lmax+i] -(kyori[lmax+i]-kyori[lmax+i-1])
    if(tmpmax_max<tmp):
        tmpmax_max=tmp
    ans.append(tmpmax+tmpmax_max)





print(max(ans))

Solution (Python):
N,C = map(int,input().split())
src = [tuple(map(int,input().split())) for i in range(N)]

cumsumr = [0]
cummaxr = [0]
cummaxr2 = [0]
px = 0
for x,v in src:
    cumsumr.append(cumsumr[-1] + v-(x-px))
    cummaxr.append(max(cummaxr[-1], cumsumr[-1]))
    cummaxr2.append(max(cummaxr2[-1], cumsumr[-1]-x))
    px = x

cumsuml = [0]
cummaxl = [0]
cummaxl2 = [0]
px = C
for x,v in src[::-1]:
    cumsuml.append(cumsuml[-1] + v-(px-x))
    cummaxl.append(max(cummaxl[-1], cumsuml[-1]))
    cummaxl2.append(max(cummaxl2[-1], cumsuml[-1]-(C-x)))
    px = x

ans = max(cummaxr[-1], cummaxl[-1])
for i in range(N):
    ans = max(ans, cummaxr2[i] + cummaxl[N-i])
    ans = max(ans, cummaxl2[i] + cummaxr[N-i])
print(ans)

Solution (Python):
def run(N, C, XV):
    '''
    左回りでxまで食べた後に、右回りのyまで食べると考える
    yは、xの次の皿まで食べることが可能なので、事前に最大
    となる食べ方を計算しておく
    逆回りも同様に計算して最大のものをとる
    '''
    
    cal_l = [0]
    cal_r = [0]
    
    cal_max_l = [0]
    cal_max_r = [0]
    cal = 0
    for i in range(N):
        cal += XV[i][1]
        cal_l.append(cal-XV[i][0]*2)
        cal_max = cal_max_l[i]
        if cal_max < cal-XV[i][0]:
            cal_max = cal-XV[i][0]
        cal_max_l.append(cal_max)
    cal = 0
    for i in range(N):
        cal += XV[N-i-1][1]
        cal_r.append(cal-(C-XV[N-i-1][0])*2)
        cal_max = cal_max_r[i]
        if cal_max < cal-C+XV[N-i-1][0]:
            cal_max = cal-C+XV[N-i-1][0]
        cal_max_r.append(cal_max)

    ret = 0
    
    for i in range(len(cal_l)):
        ret = max(ret, cal_l[i]+cal_max_r[N-i])
    
    for i in range(len(cal_r)):
        ret = max(ret, cal_r[i]+cal_max_l[N-i])
    return ret


def main():
    N, C = map(int, input().split())
    XV = []
    for i in range(N):
        XV.append(list(map(int, input().split())))
    print(run(N, C, XV))


if __name__ == '__main__':
    main()

Solution (Python):
N,C=map(int,input().split())
XV=[list(map(int,input().split())) for i in range(N)]

RIGHTSUM=[0]

for x,v in XV:
    RIGHTSUM.append(RIGHTSUM[-1]+v)

LEFTSUM=[0]

for x,v in XV[::-1]:
    LEFTSUM.append(LEFTSUM[-1]+v)

RIGHT=[]

for i in range(N):
    RIGHT.append(RIGHTSUM[i+1]-XV[i][0])

LEFT=[]

for i in range(N):
    LEFT.append(LEFTSUM[i+1]-(C-XV[-i-1][0]))


RIGHTMAX=[RIGHT[0]]

for i in range(1,N):
    RIGHTMAX.append(max(RIGHTMAX[i-1],RIGHT[i]))

LEFTMAX=[LEFT[0]]

for i in range(1,N):
    LEFTMAX.append(max(LEFTMAX[i-1],LEFT[i]))

ANS=max(max(RIGHT),max(LEFT),0)

for i in range(N-1):
    
    if ANS<(RIGHTSUM[i+1]-XV[i][0]*2)+LEFTMAX[N-i-2]:
        ANS=RIGHTSUM[i+1]-XV[i][0]*2+LEFTMAX[N-i-2]
    if ANS<LEFTSUM[i+1]-(C-XV[-i-1][0])*2+RIGHTMAX[N-i-2]:
        ANS=LEFTSUM[i+1]-(C-XV[-i-1][0])*2+RIGHTMAX[N-i-2]

print(ANS)

Solution (Python):
import sys
stdin = sys.stdin

sys.setrecursionlimit(10**5)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from itertools import accumulate

n,c = li()
x_cw = []
v_cw = []
x_ccw = []
for _ in range(n):
    x,v = li()
    x_cw.append(x)
    v_cw.append(v)
    x_ccw.append(c-x)
    
x_ccw = [0] + sorted(x_ccw)
v_ccw = [0] + v_cw[::-1]
x_cw = [0] + x_cw
v_cw = [0] + v_cw
    
for i in range(1,n+1):
    v_cw[i] += (v_cw[i-1] - (x_cw[i]-x_cw[i-1]))
    v_ccw[i] += (v_ccw[i-1] - (x_ccw[i]-x_ccw[i-1]))
    
    
max_cw = [0]
max_ccw = [0]
mx_cw = [0]
mx_ccw = [0]
for i in range(1,n+1):
    max_cw.append(max(max_cw[-1], v_cw[i]))
    max_ccw.append(max(max_ccw[-1], v_ccw[i]))
    
    if max_cw[-1] != max_cw[-2]:
        mx_cw.append(x_cw[i])
    else:
        mx_cw.append(mx_cw[-1])

    if max_ccw[-1] != max_ccw[-2]:
        mx_ccw.append(x_ccw[i])
    else:
        mx_ccw.append(mx_ccw[-1])

ans = 0
for i in range(n+1):
    temp = max_cw[i] + max_ccw[n-i] - min(mx_cw[i], mx_ccw[n-i])
    ans = max(temp, ans)

        
print(ans)

Solution (Python):
N, C = map(int, input().split())
X, V = [], []
for i in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)

st1 = [0] * N
st2 = [0] * N
st1[0] = max(0, V[0] - X[0])
st2[0] = max(0, V[0] - 2 * X[0])
cur1, cur2 = V[0] - X[0], V[0] - 2 * X[0]
pre = X[0]
for i in range(1, N):
    cur1 += V[i] - (X[i] - pre)
    cur2 += V[i] - (X[i] - pre) * 2
    st1[i] = max(st1[i - 1], cur1)
    st2[i] = max(st2[i - 1], cur2)
    pre = X[i]

ba1 = [0] * N
ba2 = [0] * N
ba1[-1] = max(0, V[-1] - (C - X[-1]))
ba2[-1] = max(0, V[-1] - 2 * (C - X[-1]))
cur1, cur2 = V[-1] - (C - X[-1]), V[-1] - 2 * (C - X[-1])
pre = X[-1]
for i in range(N - 2, -1, -1):
    cur1 += V[i] - (pre - X[i])
    cur2 += V[i] - (pre - X[i]) * 2
    ba1[i] = max(ba1[i + 1], cur1)
    ba2[i] = max(ba2[i + 1], cur2)
    pre = X[i]

num = 0
num = max(st1[N - 1], ba1[0])
for i in range(N - 1):
    num = max(num, st1[i] + ba2[i + 1])

for i in range(1, N - 1):
    num = max(num, ba1[i] + st2[i - 1])

print(num)

Solution (Python):
from itertools import accumulate
n, c = list(map(int, input().split()))
xv = [list(map(int, input().split())) for _ in range(n)]

v_cum = [0]*(n+1)
for i in range(n):
    v_cum[i+1] = v_cum[i] + xv[i][1]

for_cal = [0] + [v_cum[i+1] - xv[i][0] for i in range(n)]
fb_cal = [0] + [v_cum[i+1] - 2*xv[i][0] for i in range(n)]

for_cum = [x for x in accumulate(for_cal, max)]
fb_cum = [x for x in accumulate(fb_cal, max)]

ans = 0
for i in range(n+1):
    
    j = n if i == 0 else i-1

    
    ob_x = 0 if i == 0 else c - xv[i-1][0]
    ob_v = v_cum[n] - v_cum[i-1]

    
    ans = max(ans, fb_cum[j]+ob_v-ob_x)
    
    ans = max(ans, for_cum[j]+ob_v-2*ob_x)

print(ans)

Solution (Python):
N,C = map(int,input().split())
x1=[]
v1=[]

for i in range(N):
    x,v = map(int,input().split())
    x1.append(x)
    v1.append(v)
x2 = [C-x for x in x1]
v2 = [v for v in v1]
x2.reverse()
v2.reverse()

res1 = 0
res2 = 0
s1 = 0
s2 = 0
r1 = [0]
r2 = [0]
for i in range(N):
    s1 += v1[i]
    s2 += v2[i]
    res1 = max(res1,s1-x1[i])
    res2 = max(res2,s2-x2[i])
    r1.append(res1)
    r2.append(res2)

vl1 = [0]*(N+1)
vl2 = [0]*(N+1)
for i in range(N):
    vl1[i+1] = v2[i]+vl1[i]
    vl2[i+1] = v1[i]+vl2[i]
for i in range(N):
    vl1[i+1] -= 2*x2[i]
    vl2[i+1] -= 2*x1[i]



ans = 0
for i in range(N+1):
    res = vl1[i]+r1[N-i]
    if res > ans:
        ans = res
    res = vl2[i]+r2[N-i]
    if res > ans:
        ans = res

print(ans)

Solution (Python):
x = [0 for i in range(100001)]
v = [0 for i in range(100001)]
v_sum_right = [0 for i in range(100001)]
v_sum_left = [0 for i in range(100001)]
g = [[0, 0] for i in range(100001)]
g2= [0 for i in range(100001)]
N = 0
C = 0
i = 0
ans = 0
t = 0

N, C = [int(i) for i in input().split(" ")]
for i in range(N):
    x[i], v[i] = [int(i) for i in input().split(" ")]


v_sum_right[0] = v[0]
for i in range(1, N):
    v_sum_right[i] = v_sum_right[i - 1] + v[i]

v_sum_left[N] = 0
for i in range(N - 1, -1, -1):
    v_sum_left[i] = v_sum_left[i + 1] + v[i]



g[0][0] = 0
g[0][1] = 0
g2[0] = 0
for i in range(1, N + 1):
    g[i][0] = max(g[i - 1][0], v_sum_right[i - 1] - x[i - 1])
    g2[i] = max(g2[i - 1], v_sum_right[i - 1] - 2 * x[i - 1])
    if g[i - 1][0] == g[i][0]:
        g[i][1] = g[i - 1][1]
    else:
        g[i][1] = x[i - 1]
    

ans = v_sum_left[0] - C + x[0]
for i in range(1, N):
    ans = max(ans, v_sum_left[i] + g[i][0] - 2 * (C +- x[i]), v_sum_left[i] - C + x[i] + g2[i])
ans = max(ans, g[N][0])

print(ans)

Solution (Python):
N,C = map(int,input().split())
XV = [[0,0]] + [[int(i) for i in input().split()] for _ in range(N)] + [[C,0]]

Sum_left = [0] * (N+1)
Sum_right = [0] * (N+1)
for i in range(N):
    Sum_left[i+1] = Sum_left[i] + XV[i+1][1]
    Sum_right[i+1] = Sum_right[i] + XV[N-i][1]

Sum_right_maxA = [0] * (N+1)
Sum_right_maxB = [0] * (N+1)
for i in range(1,N+1):
    Sum_right_maxA[i] = max(Sum_right_maxA[i-1], Sum_right[i] - 2 * (C - XV[N+1-i][0]))
    Sum_right_maxB[i] = max(Sum_right_maxB[i-1], Sum_right[i] - (C - XV[N+1-i][0]))

ans = 0
for i in range(N+1):
    ans = max(ans, Sum_left[i] + Sum_right_maxA[N-i] - XV[i][0], Sum_left[i] + Sum_right_maxB[N-i] - 2*XV[i][0])
print(ans)

Solution (Python):
N, C = list(map(int,input().split()))

sushi_front = [0]
sushi_back = [0]
sushi_front2 = [0]
sushi_back2 = [0]
sushi = []

c= 0
d = 0
max_ = 0
max_2 = 0
for _ in range(N):
    sushi.append(list(map(int,input().split())))
    
    c += sushi[-1][1]
    d = sushi[-1][0]
    max_ = max(max_,c-d)
    max_2 = max(max_2, c-2*d)
    sushi_front.append(max_)
    sushi_front2.append(max_2)

sushi.reverse()
c = 0
d = 0
max_ = 0
max_2 = 0
for x in sushi:
    
    c += x[1]
    d = C -x[0]
    max_ = max(max_,c-d)
    max_2 = max(max_2, c-2*d)
    sushi_back.append(max_)
    sushi_back2.append(max_2)

ans = 0
for i in range(N+1):
    ans = max(ans,sushi_front[i]+sushi_back2[N-i],sushi_front2[i]+sushi_back[N-i])
print(ans)

Solution (Python):


n,l = list(map(int,input().split()))
D = []
C = [0]

for i in range(n):
    d,c = list(map(int,input().split()))
    D.append(d)
    C.append(C[i]+c)


L = [0]
for i in range(n):
    L.append(max(L[i],C[i+1]-D[i]))


R = [0]
for i in range(n):
    R.append(max(R[i],C[n]-C[n-i-1]-(l-D[-i-1])))


LR = 0
for i in range(n-1):
    LR = max(LR, C[i+1]-D[i]*2+R[n-i-1])


RL = 0
for i in range(n-1):
    RL = max(RL, C[n]-C[n-i-1]-(l-D[-i-1])*2+L[n-i-1])

print(max(L+R+list([LR,RL])))

Solution (Python):
def build_maxv(x, v, maxv):
    mv = 0
    sv = 0
    for i in range(len(x)):
        sv += v[i]
        mv = max(mv, sv - x[i])
        maxv.append(mv)


def build_retmaxv(x, v, retmaxv):
    mv = 0
    sv = 0
    for i in range(len(x)):
        sv += v[i]
        mv = max(mv, sv - x[i]*2)
        retmaxv.append(mv)


N, C = map(int, input().split())
ans = 0
x = []
v = []
for i in range(N):
    tx, tv = map(int, input().split())
    x.append(tx)
    v.append(tv)
x_rev = [C-i for i in x[::-1]]
v_rev = v[::-1]
maxv = []
build_maxv(x, v, maxv)
maxv_rev = []
build_maxv(x_rev, v_rev, maxv_rev)
retmaxv = []
build_retmaxv(x, v, retmaxv)
retmaxv_rev = []
build_retmaxv(x_rev, v_rev, retmaxv_rev)
ans = max(maxv[N-1], maxv_rev[N-1])
if N != 1:
    for i in range(N-1):
        t1 = maxv[i] + retmaxv_rev[N-i-2]
        t2 = maxv_rev[i] + retmaxv[N-i-2]
        ans = max(ans, t1, t2)
print(ans)

Solution (Python):
from itertools import accumulate
import sys
sdin = sys.stdin.readline

n,c = map(int, sdin().split())
x_cw = [0]
v_cw = [0]
for _ in range(n):
    x, v =  map(int, sdin().split())
    x_cw.append(x)
    v_cw.append(v)
    
v_cw_acc = list(accumulate(v_cw))    


x_ccw = [0]
v_ccw = [0]
for i in range(n):
    x_ccw.append(c-x_cw[n-i])
    v_ccw.append(v_cw[n-i])
    
v_ccw_acc = list(accumulate(v_ccw))


total_cw_max = [0]
total_ccw_max = [0]
for i in range(1,n+1):
    tmp_cw = v_cw_acc[i] - x_cw[i]
    total_cw_max.append(max(total_cw_max[-1], tmp_cw))
    
    tmp_ccw = v_ccw_acc[i] - x_ccw[i]
    total_ccw_max.append(max(total_ccw_max[-1], tmp_ccw))
    

ans_b_static = 0
for b in range(n,-1, -1):
    tmp_b_static = total_cw_max[n-b] + v_ccw_acc[b] - 2*x_ccw[b]
    ans_b_static = max(ans_b_static, tmp_b_static)
    

ans_a_static = 0
for a in range(n, -1, -1):
    tmp_a_static = total_ccw_max[n-a] + v_cw_acc[a] - 2*x_cw[a]
    ans_a_static = max(ans_a_static, tmp_a_static)
    

print(max(ans_a_static, ans_b_static))

Solution (Python):
import numpy as np
import copy
N, C = map(int, input().split())

x = np.zeros(N)
v = np.zeros(N)
for i in range(N):
    xi, vi = map(int, input().split())
    x[i] = xi
    v[i] = vi

cum_right = np.cumsum(v)
cum_left = np.cumsum(v[::-1])

max_right = np.zeros(N)
max_left = np.zeros(N)
max_right[0] = cum_right[0] - x[0]
max_left[0] = cum_left[0] - (C - x[N - 1])
for i in range(1, N):
    max_right[i] = max(max_right[i - 1], cum_right[i] - x[i])
    max_left[i] = max(max_left[i - 1], cum_left[i] - (C - x[N - 1 - i]))

ans = max(0, max_left[N - 1], max_right[N - 1])

for i in range(N - 1):
    ans = max(ans, cum_left[i] + max_right[N - 2 - i] - (C - x[N - 1 - i]) * 2)
    ans = max(ans, cum_right[i] + max_left[N - 2 - i] - x[i] * 2)
print(int(ans))

Solution (Python):
N, C = map(int, input().split())

x_list = [0, ]
v_list = [0, ]
x_oa = 0
x_2oa = 0
max_a = {0: 0}
max_2a = {0: 0}

tmp_v = 0

for i in range(N):
    x, v = map(int, input().split())

    tmp_v += v

    x_list.append(x)
    v_list.append(v)
    x_oa = max(tmp_v - x, x_oa)
    x_2oa = max(tmp_v - 2 * x, x_2oa)
    max_a[i + 1] = x_oa
    max_2a[i + 1] = x_2oa

x_list.append(C)
v_list.append(0)

tmp_v = 0
ans = 0
for i in reversed(range(1, N + 2)):

    x = x_list[i]
    v = v_list[i]
    tmp_v += v
    

    tmp_oa = tmp_v - 2 * (C - x) + max_a[i - 1]
    tmp_2oa = tmp_v - C + x + max_2a[i - 1]
    ans = max(ans, tmp_oa, tmp_2oa)

print(ans)

Solution (Python):
from itertools import accumulate

N, C = map(int, input().split())
sushi = [[int(x) for x in input().split()] for _ in range(N)]


def solve():
    """
    O(N)
    Bを固定したときの最適なAを事前に計算
    """
    V = [0] * (N + 1)
    for i in range(N):
        V[i + 1] = V[i] + sushi[i][1]

    f1 = [0] + [V[a + 1] - sushi[a][0] for a in range(N)]
    f2 = [0] + [V[a + 1] - 2 * sushi[a][0] for a in range(N)]

    g1 = [x for x in accumulate(f1, max)]
    g2 = [x for x in accumulate(f2, max)]

    ans = 0
    for j in range(N + 1):
        
        if j == 0:
            i = N
        else:
            i = j - 1

        
        if j == 0:
            ob_x = 0
        else:
            ob_x = C - sushi[j - 1][0]
        ob_v = V[N] - V[j - 1]

        
        ans = max(ans, g2[i] + ob_v - ob_x)

        
        ans = max(ans, g1[i] + ob_v - 2 * ob_x)
    print(ans)


solve()

Solution (Python):


from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def main():
    N, C = map(int, input().split())

    sushi = []
    for _ in range(N):
        x, v = map(int, input().split())
        sushi.append((x, v))

    cs_x, cs_v, cs_p = [0] * (N + 1), [0] * (N + 1), [0] * (N + 1)
    for i in range(N):
        cs_x[i + 1] = sushi[i][0]
        cs_v[i + 1] = cs_v[i] + sushi[i][1]
        cs_p[i + 1] = max(cs_p[i], cs_v[i + 1] - cs_x[i + 1])

    cs_x_rev, cs_v_rev, cs_p_rev = [0] * (N + 1), [0] * (N + 1), [0] * (N + 1)
    for i in range(N):
        cs_x_rev[i + 1] = C - sushi[-i - 1][0]
        cs_v_rev[i + 1] = cs_v_rev[i] + sushi[-i - 1][1]
        cs_p_rev[i + 1] = max(cs_p_rev[i], cs_v_rev[i + 1] - cs_x_rev[i + 1])


    
    
    
    

    
    ans = 0
    for i in range(1, N + 1):
        total_x = cs_x[i]
        total_v = cs_v[i]
        profit = total_v - total_x
        ans = max(ans, profit)

        profit -= total_x
        profit += cs_p_rev[N - i]
        ans = max(ans, profit)

    
    for i in range(1, N + 1):
        total_x = cs_x_rev[i]
        total_v = cs_v_rev[i]
        profit = total_v - total_x
        ans = max(ans, profit)

        profit -= total_x
        profit += cs_p[N - i]
        ans = max(ans, profit)

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np
n, c = list(map(int, input().split()))
xv = list(list(map(int, input().split())) for i in range(n))
sushi1, max1, sushi2, max2 = [0], [0], [0], [0]
sum1, sum2 = 0, 0
for x, v in xv:
    sum1 += v
    sushi1.append(max(sum1 - x, sushi1[-1]))
    max1.append(max(sum1 - 2*x, max1[-1]))
for x, v in xv[::-1]:
    sum2 += v
    sushi2.append(max(sum2 - (c-x), sushi2[-1]))
    max2.append(max(sum2 - 2*(c-x), max2[-1]))
ans1 = max(np.array(sushi1) + np.array(max2[::-1]))
ans2 = max(np.array(sushi2) + np.array(max1[::-1]))
print(max(0, ans1, ans2))

Solution (Python):

from collections import defaultdict
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
AtoZ = [chr(i) for i in range(65,65+26)]
atoz = [chr(i) for i in range(97,97+26)]

def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N,C = inpl()
xv = [inpl() for i in range(N)]



rc = rd = lc = ld = 0
ans = 0
R1 = [0]
L1 = [0]
R2 = [0]
L2 = [0]
MAX_R1 = MAX_R2 = MAX_L1 = MAX_L2 = -INF
for i in range(0,N):
	x,v = xv[i]
	rd = x
	rc += v
	MAX_R1 = max(MAX_R1,rc-rd)
	MAX_R2 = max(MAX_R2,rc-2*rd)
	R1.append(MAX_R1)
	R2.append(MAX_R2)

	x,v = xv[N-1-i]
	ld = C-x
	lc += v
	MAX_L1 = max(MAX_L1,lc-ld)
	MAX_L2 = max(MAX_L2,lc-2*ld)
	L1.append(MAX_L1)
	L2.append(MAX_L2)

ans = 0
for i in range(0,N+1):
	r1 = R1[i]
	r2 = R2[i]
	l1 = L1[N-i]
	l2 = L2[N-i]
	ans1 = r2 + l1
	ans2 = r1 + l2
	ans = max(r1,l1,ans1,ans2,ans)

print(ans)

Solution (Python):
import numpy as np
def hanten(C, X, V):
	return (C*np.ones(X.shape[0])-X)[::-1], V[::-1]

def solv2(N, X, V):
	r = 0
	rbuf = 0
	pos = 0
	Vsum = V.copy()
	for i in range(N):
		rbuf += V[i] - (X[i]-pos)
		pos = X[i]
		if(rbuf > r):
			r = rbuf
		Vsum[i] = r
	return Vsum

def solv(N, C, X, V):
	r = 0
	rbuf1 = 0
	pos = 0
	ibuf = 0
	iX, iV = hanten(C, X, V) 
	iv = solv2(N, iX, iV)
	
	for i in range(N):
		rbuf1 += V[i] - 2*(X[i]-pos)
		rbuf2 = iv[N-(i+2)]
		if(i == N-1):
			rbuf2 = 0
		rbuf = rbuf1 + rbuf2
		pos = X[i]
		
		if(rbuf > r):
			r = rbuf
	return max(r, iv[-1])
	
def main():
	buf = input().split()
	N = int(buf[0])
	C = int(buf[1])
	X = np.zeros(N)
	V = np.zeros(N)
	for i in range(N):
		buf = input().split()
		X[i] = int(buf[0])
		V[i] = int(buf[1])
	r1 = solv(N, C, X, V)
	X, V = hanten(C, X, V)
	r2 = solv(N, C, X, V)
	print(int(max(r1, r2)))
	
main()

Solution (Python):
N,C = map(int,input().split())
X,V = [],[]
for i in range(N):
    x,v = map(int,input().split())
    X.append(x)
    V.append(v)
Ans = 0


xR = [0]+X
xL = [0]+list(map(lambda x: C-x,reversed(X)))


V2 = list(reversed(V))
calR,calL = [0],[0]
for i in range(N):
    calR.append(calR[i]+V[i])
    calL.append(calL[i]+V2[i])


getR,getL = [],[]
for i in range(N+1):
    getR.append(calR[i]-xR[i])
    getL.append(calL[i]-xL[i])

for i in range(N):
    if getR[i+1] < getR[i]:
        getR[i+1] = getR[i]
    if getL[i+1] < getL[i]:
        getL[i+1] = getL[i]

for i in range(N+1):
    gr = getR[N-i]
    gl = getL[i]
    xr = xR[N-i]
    xl = xL[i]
    
    Ans = max(Ans, gr, gr-xr+gl)
    
    Ans = max(Ans, gl, gl-xl+gr)

print(Ans)

Solution (Python):
import numpy as np

n,c=map(int,input().split())
x0=[]
v0=[0]
for _ in range(n):
	i,j=map(int,input().split())
	x0.append(i)
	v0.append(j+v0[_])
x=np.array([0]+x0)
y=np.full_like(x,c)-np.array(x0+[c])
v=np.array(v0)
w=np.full_like(v,v[n])-v

s=v-x
t=w-y
k=x.searchsorted(-((-c)//2))
a0=[np.max(t[k-1:])]
for i in range(k-1)[::-1]:
	a0.append(max(a0[-1],t[i]))
b0=[np.max(s[:k])]
for i in range(k,n+1):
	b0.append(max(b0[-1],s[i]))
print(max(np.max(s[:k]-x[:k]+np.array(a0)[::-1]),
	np.max(t[k-1:]-y[k-1:]+np.array(b0))))

Solution (Python):
N,C=map(int,input().split())
L=[list(map(int,input().split())) for _ in range(N)]
cal_list=[]
dis_list=[]
cal_list.append(0)
dis_list.append(0)
for i in range(N):
    dis_list.append(L[i][0])
    cal_list.append(L[i][1])
    
dis_list.append(C)

time_around=[0 for _ in range(N+1)]
time_around_rev=[0 for _ in range(N+1)]
time_around_temp=0
for i in range(1,N+1):
    time_around[i]=time_around[i-1]+(cal_list[i]-(dis_list[i]-dis_list[i-1]))
    if time_around_temp<time_around[i]-dis_list[i]:
        time_around_rev[i]=time_around[i]-dis_list[i]
        time_around_temp=time_around[i]-dis_list[i]
        
    else:
        time_around_rev[i]=time_around_temp

time_rev_around=[0 for _ in range(N+1)]
time_rev_around_rev=[0 for _ in range(N+1)]
time_rev_around_temp=0
for i in range(1,N+1):
    time_rev_around[i]=time_rev_around[i-1]+(cal_list[N-i+1]-(dis_list[N-i+2]-dis_list[N-i+1]))
    if time_rev_around_temp< time_rev_around[i]-(C-dis_list[N-i+1]):
        time_rev_around_rev[i]=time_rev_around[i]-(C-dis_list[N-i+1])
        time_rev_around_temp=time_rev_around_rev[i]
    else:
        time_rev_around_rev[i]=time_rev_around_temp
        

result=0
for i in range(1,N+1):
    result=max((time_around[i]+time_rev_around_rev[N-i]),(time_rev_around[i]+time_around_rev[N-i]),result)
    
print(result)

Solution (Python):
n, c = map(int, input().split())

x = [0 for _ in range(n + 2)]
v = [0 for _ in range(n + 1)]
for i in range(n):
    x[i + 1], v[i + 1] = map(int, input().split())

x[n + 1] = c

left = [0 for _ in range(n + 1)]
right = [0 for _ in range(n + 1)]
left_rev = [0 for _ in range(n + 1)]
right_rev = [0 for _ in range(n + 1)]

left_temp = 0
right_temp = 0
for i in range(1, n + 1):
    left[i] = left[i - 1] + v[i] - (x[i] - x[i - 1])
    if left_temp < left[i] - x[i]:
        left_rev[i] = left[i] - x[i]
        left_temp = left_rev[i]
    else:
        left_rev[i] = left_temp
    right[i] = right[i - 1] + v[n - i + 1] - (x[n - i + 2] - x[n - i + 1])
    if right_temp < right[i] - (c - x[n - i + 1]):
        right_rev[i] = right[i] - (c - x[n - i + 1])
        right_temp = right_rev[i]
    else:
        right_rev[i] = right_temp

result = 0
for i in range(1, n + 1):
    result = max( (left[i] + right_rev[n - i]) , (right[i] + left_rev[n - i]) , result )

print(result)

Solution (Python):
from itertools import accumulate, chain
 
n, c = map(int, input().split())
xs, vs = zip(*(map(int, input().split()) for _ in range(n)))
 
ds = [j - i for i, j in zip(chain([0], xs), chain(xs, [c]))]
 
clockwise1      = chain([0], (v - d*2 for v, d in zip(accumulate(vs), accumulate(ds))))
anticlockwise1  = chain([0], (v - d for v, d in zip(accumulate(vs[::-1]), accumulate(ds[::-1]))))
clock_anticlock = (x + y for x, y in zip(clockwise1, reversed(list(accumulate(anticlockwise1, func=max)))))
 
anticlockwise2  = chain([0], (v - d*2 for v, d in zip(accumulate(vs[::-1]), accumulate(ds[::-1]))))
clockwise2      = chain([0], (v - d for v, d in zip(accumulate(vs), accumulate(ds))))
anticlock_clock = (x + y for x, y in zip(anticlockwise2, reversed(list(accumulate(clockwise2, func=max)))))
 
print(max(chain(clock_anticlock, anticlock_clock)))

Solution (Python):
from itertools import accumulate, chain

n, c = map(int, input().split())
xs, vs = zip(*(map(int, input().split()) for _ in range(n)))

ds = [j - i for i, j in zip(chain([0], xs), chain(xs, [c]))]

clockwise1      = chain([0], (v - d*2 for v, d in zip(accumulate(vs), accumulate(ds))))
anticlockwise1  = chain([0], (v - d for v, d in zip(accumulate(vs[::-1]), accumulate(ds[::-1]))))
clock_anticlock = (x + y for x, y in zip(clockwise1, reversed(list(accumulate(anticlockwise1, func=max)))))

anticlockwise2  = chain([0], (v - d*2 for v, d in zip(accumulate(vs[::-1]), accumulate(ds[::-1]))))
clockwise2      = chain([0], (v - d for v, d in zip(accumulate(vs), accumulate(ds))))
anticlock_clock = (x + y for x, y in zip(anticlockwise2, reversed(list(accumulate(clockwise2, func=max)))))
 
print(max(chain(anticlock_clock, clock_anticlock)))

Solution (Python):
from itertools import accumulate, chain

n, c = map(int, input().split())
xs, vs = zip(*(map(int, input().split()) for _ in range(n)))

ds = [j - i for i, j in zip(chain([0], xs), chain(xs, [c]))]

clockwise1      = [0] + [v - d*2 for v, d in zip(accumulate(vs), accumulate(ds))]
anticlockwise1  = [0] + [v - d for v, d in zip(accumulate(vs[::-1]), accumulate(ds[::-1]))]
clock_anticlock = (x + y for x, y in zip(clockwise1, reversed(list(accumulate(anticlockwise1, func=max)))))

anticlockwise2  = [0] + [v - d*2 for v, d in zip(accumulate(vs[::-1]), accumulate(ds[::-1]))]
clockwise2      = [0] + [v - d for v, d in zip(accumulate(vs), accumulate(ds))]
anticlock_clock = (x + y for x, y in zip(anticlockwise2, reversed(list(accumulate(clockwise2, func=max)))))
 
print(max(chain(anticlock_clock, clock_anticlock)))