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):
"""
カウンターの回り方はパターンが多すぎるので、考えない方がよい。
考え方１：
残っている寿司のうち、そこにたどり着くまでのエネルギー <= そこにたどり着くまでに摂取できる寿司のカロリー
となるような寿司があるかどうか。


考え方２：
二分探索。
X以上カロリーを得できるか、という二分探索。

考え方３：
動き方のパターンは4つある。
時計回りに動いて、どこかのタイミングで退店
半時計周りに動いて、どこかのタイミングで退店
時計回りに動いた後、反時計回りに動いて退店
反時計回りに動いた後、時計回りに動いて退店
それぞれのパターンで動く場合の最大価値を求める。
これで行こう
"""

N,C = map(int,input().split())


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

ans = 0
"""
まずは時計回りに動いてどこかのタイミングで退店する場合を考える。
これは、時計回りに寿司を見て行って、各寿司にたどり着いた時の、摂取カロリーの累積和と消費カロリーを求めればよい。
"""

cal = 0
for x,v in sushi:
    cal += v
    ans = max(ans,cal-x)

"""
次に反時計回りに動いてどこかのタイミングで退店する場合を考える。
"""
cal = 0
for x,v in sushiR:
    cal += v
    ans = max(ans,cal-x)


"""
時計回りに動いた後、反時計回りに動いて退店する場合を考える。
これは、時計回りでどこまで動くか（つまりどこで折り返すか）で場合わけし、
各地点で折り返す場合に、反時計回りでどこまで行くのがベストなのかをaccumSushiRをつかって判断する
"""
from heapq import heappop,heappush
sushiRQue = []
cal = 0
for i in range(N):
    x,v = sushiR[i]
    cal += v
    heappush(sushiRQue,(-(cal-x),i))

cal = 0
for i in range(N-1):
    x,v = sushi[i]
    cal += v
    while sushiRQue[0][1]+i >= N-1:
        heappop(sushiRQue)
    ans = max(ans,cal-x*2+(-sushiRQue[0][0]))

"""
時計回りに動いた後、反時計回りに動いて退店する場合を考える。
これは、時計回りでどこまで動くか（つまりどこで折り返すか）で場合わけし、
各地点で折り返す場合に、反時計回りでどこまで行くのがベストなのかをaccumSushiRをつかって判断する
"""
sushiQue = []
cal = 0
for i in range(N):
    x,v = sushi[i]
    cal += v
    heappush(sushiQue,(-(cal-x),i))

cal = 0
for i in range(N-1):
    x,v = sushiR[i]
    cal += v
    while sushiQue[0][1]+i >= N-1:
        heappop(sushiQue)
    ans = max(ans,cal-x*2+(-sushiQue[0][0]))

print(ans)

Solution (Python):
n,c1 = map(int, input().split())
g = []
c = [0]
d = [0]
a = 0
ans=[]
m1=0
m2=0
for i in range(n):
  x,v = map(int, input().split())
  g.append([x,v])
  a+=v
  m1= max(a-x,m1)
  m2= max(a-2*x,m2)
  c.append(m1)
  d.append(m2)
b = 0
e = [0]
f = [0]
for i,j in reversed(g):
  b+=j
  e.append(b-(c1-i))
  f.append(b-2*(c1-i))
for i in range(n+1):
  ans.append(c[i]+f[-i-1])
  ans.append(d[i]+e[-i-1])
print(max(ans))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



N, C = MAP()
xv = [LIST() for _ in range(N)]


energy_left_1 = [0]
energy_left_2 = [0]
tmp_v = 0
for x, v in xv:
	tmp_v += v
	energy_left_1.append(tmp_v-x)
	energy_left_2.append(tmp_v-2*x)


energy_right_1 = [0]
energy_right_2 = [0]
tmp_v = 0 
for x, v in xv[::-1]:
	y = C-x
	tmp_v += v
	energy_right_1.append(tmp_v-y)
	energy_right_2.append(tmp_v-2*y)

energy_left_1_acc = list(accumulate(energy_left_1, max))
energy_left_2_acc = list(accumulate(energy_left_2, max))
energy_right_1_acc = list(accumulate(energy_right_1, max))
energy_right_2_acc = list(accumulate(energy_right_2, max))

ans = -INF
for i in range(N+1):
	ans = max(ans, energy_left_1_acc[i]+energy_right_2_acc[N-i])
	ans = max(ans, energy_left_2_acc[i]+energy_right_1_acc[N-i])
print(ans)

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

av = 0
fa1 = 0
bv = 0
fb1 = 0
fa = []
fb = []
ga = []
gb = []
for i in range(N):
    ax = xv[i][0]
    av += xv[i][1]
    bx = C - xv[-(i+1)][0]
    bv += xv[-(i+1)][1]
    fa1 = max(fa1, av-ax)
    fa.append(fa1)
    ga.append(av - 2*ax)
    fb1 = max(fb1, bv-bx)
    fb.append(fb1)
    gb.append(bv - 2*bx)

p = max(0, fa[-1], fb[-1])

for i in range(N-1):
    p = max(p, fa[i]+gb[N-i-2], ga[i]+fb[N-i-2])

print(p)

Solution (Python):
n,c = list(map(int,input().split()))
xv = [list(map(int,input().split())) for i in range(n)]

frontGet = [0]*n
frontRuiseki = [0]*(n+1)
backGet = [0]*n
backRuiseki = [0]*(n+1)

for i in range(n):
    frontRuiseki[i+1] = frontRuiseki[i]+xv[i][1] 
    frontGet[i] = frontRuiseki[i+1] - xv[i][0]
    idx = -1 - i
    backRuiseki[idx-1] = backRuiseki[idx]+xv[idx][1] 
    backGet[idx] = backRuiseki[idx-1] + xv[idx][0] - c

backGet.reverse()
frontGet = [0] + frontGet
backGet = [0] + backGet
xv = [[0,0]] + xv
frontMax = [0]*(n+1)
backMax = [0]*(n+1)

for i in range(n):
    frontMax[i+1] = max(frontMax[i],frontGet[i+1])
    backMax[i+1] = max(backGet[i+1],backMax[i])

ans = max(frontMax[-1],backMax[-1],0)
for i in range(n+1):
    front = frontGet[i] - xv[i][0]
    front += backMax[n - i]
    back = backGet[i] + xv[-i][0] - c
    back += frontMax[n - i]
    ans = max(ans,front,back)
print(ans)

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

A,B=[],[]
allv=0
for i in range(N):
  a,b=map(int, input().split())
  A.append([a,b])
  B.append([C-a,b])
  allv+=b
A,B=sorted(A),sorted(B)
OA,OB,AS,BS=[],[],[],[]
ax,av,bx,bv=0,0,0,0
for i in range(N):
  ax,bx=A[i][0],B[i][0]
  av+=A[i][1]
  bv+=B[i][1]
  OA.append((ax,av))
  OB.append((bx,bv))
  AS.append(av-ax)
  BS.append(bv-bx)

d=BS[0]
e=AS[0]
BSma,ASma=[-10000]*N,[-10000]*N
for i in range(N):
  BSma[i]=max(d,BS[i])
  d=BSma[i]
  ASma[i]=max(e,AS[i])
  e=ASma[i]
  
ansa=0
for i in range(N-1):
  
  bma=N-i
  oa=OA[i][1]-OA[i][0]
  ao=-OA[i][0]
  ob=BSma[-2-i]
  d=max(oa,oa+ao+ob)
  ansa=max(ansa,d)
ansb=0
for i in range(N-1):
  
  ama=N-i
  ob=OB[i][1]-OB[i][0]
  bo=-OB[i][0]
  oa=ASma[-2-i]
  d=max(ob,ob+bo+oa)
  ansb=max(ansb,d)
print(max(ansa,ansb,allv-(C-max(OA[0][0],OB[0][0]))))

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

A,B=[],[]
allv=0
for i in range(N):
  a,b=map(int, input().split())
  A.append([a,b])
  B.append([C-a,b])
  allv+=b
A,B=sorted(A),sorted(B)
OA,OB,AS,BS=[],[],[],[]
ax,av,bx,bv=0,0,0,0
for i in range(N):
  ax,bx=A[i][0],B[i][0]
  av+=A[i][1]
  bv+=B[i][1]
  OA.append((ax,av))
  OB.append((bx,bv))
  AS.append(av-ax)
  BS.append(bv-bx)

d=BS[0]
e=AS[0]
BSma,ASma=[-10000]*N,[-10000]*N
for i in range(N):
  BSma[i]=max(d,BS[i])
  d=BSma[i]
  ASma[i]=max(e,AS[i])
  e=ASma[i]
  
ansa=0
for i in range(N-1):
  
  bma=N-i
  oa=OA[i][1]-OA[i][0]
  ao=-OA[i][0]
  ob=BSma[-2-i]
  d=max(oa,oa+ao+ob)
  ansa=max(ansa,d)
ansb=0
for i in range(N-1):
  
  ama=N-i
  ob=OB[i][1]-OB[i][0]
  bo=-OB[i][0]
  oa=ASma[-2-i]
  d=max(ob,ob+bo+oa)
  ansb=max(ansb,d)
print(max(ansa,ansb,allv-(C-max(OA[0][0],OB[0][0]))))

Solution (Python):
import numpy as np
import sys
input2 = sys.stdin.read


n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]

XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RXA, RXB = XA - A, XB - B    

MA = np.zeros(n + 1, dtype=np.int64)
MB = np.zeros(n + 1, dtype=np.int64)
MRA = np.zeros(n + 1, dtype=np.int64)
MRB = np.zeros(n + 1, dtype=np.int64)


def max_mem(lis, mlis):
    for i in range(n):
        mlis[i + 1] = max(mlis[i], lis[i])


max_mem(XA, MA)
max_mem(XB, MB)
max_mem(RXA, MRA)
max_mem(RXB, MRB)

if n == 1:
    print(MA[1])
    exit()



res1, res2 = 0, 0
for i in range(n + 1):
    res1 = max(res1, MA[i] + MRB[n - i])
    res2 = max(res2, MB[i] + MRA[n - i])
    

print(max(res1, res2))

Solution (Python):
import numpy as np
import sys
input2 = sys.stdin.read


n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]

XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RXA, RXB = XA - A, XB - B    
NMA, NMB = XA.max(), XB.max()


def ind(lis, maxi):
    for i, x in enumerate(lis):
        if x == maxi:
            return i


MRA2, MRB2 = max(RXA[:-1], default=0), max(RXB[:-1], default=0)
mrai = ind(RXA, MRA2)
mrbi = ind(RXB, MRB2)

if not mrai and not mrbi:
    mrai, mrbi = 0, 0

MA2 = max(0, max(XA[:n - 1 - mrbi], default=0))
MB2 = max(0, max(XB[:n - 1 - mrai], default=0))
res = max(NMA, NMB, MA2 + MRB2, MB2 + MRA2)


for k in range(-1, -10 if n > 10 else -2, -1):
    MA3, MB3 = max(XA[:k], default=0), max(XB[:k], default=0)
    mai3 = ind(XA, MA3)
    mbi3 = ind(XB, MB3)

    if not mai3 and not mbi3:
        mai3, mbi3 = 0, 0

    MRA3 = max(0, max(RXA[:n - 1 - mbi3], default=0))
    MRB3 = max(0, max(RXB[:n - 1 - mai3], default=0))

    res = max(res, MA3 + MRB3, MB3 + MRA3)
print(res)

Solution (Python):
n,c=map(int,input().split())
rl=[[0]*2 for _ in range(n+1)]
ls,rs=0,0
xv=[[0,0]]+[list(map(int,input().split())) for _ in range(n)]
for i in range(1,n+1):
    j,k=xv[i]
    rs+=k
    rl[i][0],rl[i][1]=max(rl[i-1][0],rs-j),max(rl[i-1][1],rs-2*j)
ans=rl[n][0]
for i in range(n):
    ls+=xv[n-i][1]
    ans=max(ans,rl[n-i-1][1]+ls-(c-xv[n-i][0]),rl[n-i-1][0]+ls-(c-xv[n-i][0])*2)
print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N, C = map(int, input().split())
    X = []
    V = []
    for _ in range(N):
        x, v = map(int, input().split())
        X.append(x)
        V.append(v)

    
    dp_right = [0] * N
    dp_right[0] = -X[0] + V[0]
    for i in range(1, N):
        dp_right[i] = dp_right[i - 1] + V[i] - (X[i] - X[i - 1])

    
    dp_left = [0] * N
    dp_left[N - 1] = V[N - 1] - (C - X[N - 1])
    for i in range(N - 2, -1, -1):
        dp_left[i] = dp_left[i + 1] + V[i] - (X[i + 1] - X[i])

    
    for i in range(1, N):
        if dp_right[i] >= dp_right[i - 1]:
            continue
        else:
            dp_right[i] = dp_right[i - 1]

    for i in range(N - 2, -1, -1):
        if dp_left[i] >= dp_left[i + 1]:
            continue
        else:
            dp_left[i] = dp_left[i + 1]

    
    ans = max(0, dp_left[0], dp_right[-1])
    
    for i in range(N - 1):
        tmp = dp_right[i] + dp_left[i + 1] - X[i]
        if tmp > ans:
            ans = tmp

    
    for i in range(N - 1, 0, -1):
        tmp = dp_left[i] + dp_right[i - 1] - (C - X[i])
        if tmp > ans:
            ans = tmp

    print(ans)


if __name__ == "__main__":
    main()

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

x = []
v = []
array1 = []
array2 = []

for i in range(n):
  a,b = map(int, input().split())
  x.append(a)
  v.append(b)
  
rx = []
rv = []
for i in reversed(range(len(x))):
  rx.append(c-x[i])
  rv.append(v[i])
  
count = x[0]
array1.append(v[0] - x[0])
for i in range(1,n):
  array1.append(v[i]-x[i]+array1[i-1]+count)
  count = x[i]
  
count = rx[0]
array2.append(rv[0] - rx[0])
for i in range(1,n):
  array2.append(rv[i]-rx[i]+array2[i-1]+count)
  count = rx[i]

num = 0
max_array = []
for i in range(len(array1)-1):
  num = max(num, array1[i])
  max_array.append(num)

max_array = list(reversed(max_array))

num = 0
rmax_array = []
for i in range(len(array2)-1):
  num = max(num, array2[i])
  rmax_array.append(num)
  
rmax_array = list(reversed(rmax_array))
  
  
ans = 0
for i in range(n):
  if i != n-1:
    tmp = max(array1[i], array1[i]-x[i]+rmax_array[i])
    ans = max(ans, tmp)
  else:
    ans = max(ans, array1[i])
  
for i in range(n):
  if i != n-1:
    tmp = max(array2[i], array2[i]-rx[i]+max_array[i])
    ans = max(ans, tmp)
  else:
    ans = max(ans, array2[i])
    
print(ans)

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

N,C, *XV = map(int, read().split())
X=XV[::2]
V=XV[1::2]

m1=[0]
m2=[0]

s=0
ans=0
for x,v in zip(X,V):
    s+=v
    ans=max(ans,s-x)
    m1.append(max(m1[-1],s-x))
    m2.append(max(m2[-1],s-2*x))
s=0
i=0
for x,v in reversed(list(zip(X,V))):
    s+=v
    x=C-x
    ans=max(ans,s-2*x+m1[-2-i],s-x+m2[-2-i])
    i+=1
print(ans)

Solution (Python):
n,c = map(int,input().split())
x = [list(map(int,input().split())) for i in range(n)]

rcur = 0
lcur = 0
rmax = 0
lmax = 0
r = [[0,0]]
for i in range(n):
    a,b = x[i]
    rcur += b
    lcur = a
    if rmax < rcur-lcur:
        rmax = rcur-lcur
        lmax = lcur
    r.append([rmax,lmax])

rcur = 0
lcur = 0
rmax = 0
lmax = 0
l = [[0,0] for i in range(n+1)]
for i in range(1,n+1):
    a,b = x[-i]
    rcur += b
    lcur = c-a
    if rmax < rcur-lcur:
        rmax = rcur-lcur
        lmax = lcur
    l[-1-i] = [rmax,lmax]


ans = 0

for i in range(n+1):
    count = l[i][0]+r[i][0] - min(l[i][1],r[i][1])
    ans = max(ans,count)
    
print(ans)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,C = LI()
    a = [LI() for _ in range(n)]
    u = [_[0] for _ in a]
    x = [_[1] for _ in a]
    b = [0] * n
    c = [0] * n
    d = [0] * n
    e = [0] * n
    b[0] = x[0]
    c[-1] = x[-1]
    for i in range(1, n):
        b[i] = b[i-1] + x[i]
    for i in range(n-2, -1, -1):
        c[i] = c[i+1] + x[i]
    d[0] = x[0] - u[0]
    e[-1] = x[-1] - (C-u[-1])
    for i in range(1, n):
        d[i] = max(b[i]-u[i], d[i-1])
    for i in range(n-2, -1, -1):
        e[i] = max(c[i]-(C-u[i]), e[i+1])

    r = max(d[-1], e[0], 0)
    for i in range(n):
        if i < n-1 and r < b[i] - u[i] * 2 + e[i+1]:
            r = b[i] - u[i] * 2 + e[i+1]
        if i > 0 and r < c[i] - (C-u[i]) * 2 + d[i-1]:
            r = c[i] - (C-u[i]) * 2 + d[i-1]


    return r



print(main())

Solution (Python):



N, C = list(map(int, input().split()))
X, V = [0] * (N + 1), [None] * N
for i in range(N):
    X[i + 1], V[i] = list(map(int, input().split()))


def main():
    Vsum = [0] * (N + 1)
    for i in range(N):
        Vsum[i + 1] = Vsum[i] + V[i]
    
    A, B = [0] * (N + 1), [0] * (N + 1)
    for i in range(1, N + 1):
        A[i] = max(A[i - 1], Vsum[i] - X[i])
        B[i] = max(B[i - 1], Vsum[-1] - Vsum[-1 - i] - (C - X[-i]))
    
    ans = 0
    for i in range(1, N):
        ans = max(ans, A[i] + B[N - i] - X[i])
    for i in range(1, N):
        ans = max(ans, B[i] + A[N - i] - (C - X[-i]))
    ans = max(ans, A[N])
    ans = max(ans, B[N])

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


N, C = list(map(int, sys.stdin.buffer.readline().split()))
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]

XY.sort()
XY = np.array(XY, dtype=int)
X = XY[:, 0]
Y = XY[:, 1]


lefts = np.zeros(N + 1, dtype=int)
rights = np.zeros(N + 1, dtype=int)
lefts[1:] = np.maximum.accumulate(Y.cumsum() - X)
rights[1:] = Y[::-1].cumsum() - (C - X[::-1]) * 2
ans1 = max(lefts + rights[::-1])


lefts = np.zeros(N + 1, dtype=int)
rights = np.zeros(N + 1, dtype=int)
lefts[1:] = Y.cumsum() - X * 2
rights[1:] = np.maximum.accumulate(Y[::-1].cumsum() - (C - X[::-1]))
ans2 = max(lefts + rights[::-1])

ans = max(ans1, ans2, 0)
print(ans)

Solution (Python):
n,c = map(int,input().split())
xv = [ tuple(map(int, input().split())) for _ in range(n)]

go = [[0] * (n+1) for _ in range(2)]
turn = [[0] * (n+1) for _ in range(2)]

tmp = 0
g_max = 0
t_max = 0
for i in range(1,n+1):
    tmp += xv[i-1][1]
    go[0][i] = g_max = max(tmp - xv[i-1][0], g_max)
    turn[0][i] = t_max = max(tmp - xv[i-1][0] * 2, t_max)
    
tmp = 0
g_max = 0
t_max = 0
for i in range(n, 0, -1):
    tmp += xv[i-1][1]
    go[1][i] = g_max = max(tmp - (c - xv[i-1][0]), g_max)
    turn[1][i] = t_max = max(tmp - (c - xv[i-1][0]) * 2, t_max)

ans = 0
for i in range(1, n+1):
    ans = max(go[0][i] + turn[1][(i+1)%(n+1)], ans)
    ans = max(go[1][i] + turn[0][i-1], ans)
    
print(ans)

Solution (Python):
n,c=map(int,input().split())
xv=[list(map(int,input().split())) for i in range(n)]
fa=[0]*(n+1)
ga=[0]*(n+1)
fb=[0]*(n+1)
gb=[0]*(n+1)
ans1=0
ans2=0
fa[1]=xv[0][1]-xv[0][0]
ga[1]=max(fa[1],fa[0])
fb[1]=xv[-1][1]-(c-xv[-1][0])
gb[1]=max(fb[0],fb[1])
for i in range(1,n):
  fa[i+1]=fa[i]+xv[i][1]-(xv[i][0]-xv[i-1][0])
  ga[i+1]=max(ga[i],fa[i+1])
  fb[i+1]=fb[i]+xv[-i-1][1]-(xv[-i][0]-xv[-i-1][0])
  gb[i+1]=max(gb[i],fb[i+1])
ans1=ga[n]
ans2=gb[n]
for i in range(0,n):
  ans1=max(ans1,ga[i]+fb[n-i]-(c-xv[-n+i][0]))
  ans2=max(ans2,gb[i]+fa[n-i]-xv[n-i-1][0])
print(max(ans1,ans2))

Solution (Python):

N,C = map(int,input().split())

xv = []

for i in range(N):

    x,v = map(int,input().split())
    xv.append([x,v])

xv.sort()

ldis = [0]
lcal = [0]

for i in range(N):

    ldis.append(xv[i][0])
    lcal.append(lcal[-1] + xv[i][1])

lmax = [0]
for i in range(N):
    i += 1
    lmax.append( max(lmax[-1] , lcal[i] - ldis[i]) )

rdis = [0]
rcal = [0]

for i in range(N):
    i = N-1-i
    rdis.append(C - xv[i][0])
    rcal.append(rcal[-1] + xv[i][1])

rmax = [0]
for i in range(N):
    i += 1
    rmax.append ( max(rmax[-1] , rcal[i] - rdis[i]) )

lmax2 = [0]
for i in range(N):
    i += 1
    lmax2.append( max(lmax2[-1] , lcal[i] - ldis[i] * 2) )
rmax2 = [0]
for i in range(N):
    i += 1
    rmax2.append ( max(rmax2[-1] , rcal[i] - rdis[i] * 2) )

ans = 0
for i in range(N+1):

    if i != N-i:
        ans = max(ans,lmax[i] + rmax2[N-i],lmax2[i] + rmax[N-i])


print (ans)

Solution (Python):
from itertools import accumulate
N, C = map(int, input().split())
xs = [0]
ys = [0]
vs = [0]
us = [0]
ws = [0]
for i in range(N):
    x, v = map(int, input().split())
    us.append(us[-1]+v-x+xs[-1])
    vs.append(v)
    xs.append(x)
for i in range(N, 0, -1):
    y = C-xs[i]
    ws.append(ws[-1]+vs[i]-y+ys[-1])
    ys.append(y)


zs = [0] * (N+1)
c = 0
r = 0
for i, u in enumerate(us):
    if c <= u:
        c, ci = u, i
        r = max(r, c)
    zs[i] = (c, ci)
zs2 = [0] * (N+1)
c = 0
for i, u in enumerate(ws):
    if c <= u:
        c, ci = u, i
        r = max(r, c)
    zs2[i] = (c, ci)
for z, zi in zs:
    
    c = z+zs2[N-zi][0]-xs[zi]
    r = max(r, c)
for z, zi in zs2:
    
    c = z+zs[N-zi][0]-ys[zi]
    r = max(r, c)

print(r)

Solution (Python):
import copy

N, C= map(int,input().split())
XV = sorted([list(map(int,input().split())) for _ in range(N)])
acmXV = []
dbl_acmXV = []

for i, xv in enumerate(XV):
  x,v = xv
  if i == 0:
    acmXV.append(v-x)
    dbl_acmXV.append(v-x*2)
  else:
    acmXV.append(v-(x-XV[i-1][0])+acmXV[i-1])
    dbl_acmXV.append(v-(x-XV[i-1][0])*2+dbl_acmXV[i-1])

acmXV_rev = [0 for _ in range(N)]
dbl_acmXV_rev = [0 for _ in range(N)]
for i in range(N-1, -1, -1):
  x,v = XV[i]
  if i == N-1:
    acmXV_rev[i] = v-(C-x)
    dbl_acmXV_rev[i] = v-(C-x)*2
  else:
    acmXV_rev[i] = (v-(XV[i+1][0]-XV[i][0])+acmXV_rev[i+1])
    dbl_acmXV_rev[i] = (v-(XV[i+1][0]-XV[i][0])*2+dbl_acmXV_rev[i+1])


max_acmXV_rev = copy.deepcopy(acmXV_rev)
max_dbl_acmXV_rev = copy.deepcopy(dbl_acmXV_rev)
for i in range(N-2,-1,-1):
  max_acmXV_rev[i] = max(max_acmXV_rev[i], max_acmXV_rev[i+1])
  max_dbl_acmXV_rev[i] = max(max_dbl_acmXV_rev[i],max_dbl_acmXV_rev[i+1])

ans = max(0,max(acmXV),max(acmXV_rev))
for i in range(N-1):
  ans = max(ans, dbl_acmXV[i]+max_acmXV_rev[i+1], acmXV[i]+max_dbl_acmXV_rev[i+1]) 
print(ans)

Solution (Python):
import numpy as np
import sys
input = sys.stdin.buffer.readline
N,C= map(int,input().split())
x, v = np.array([list(map(int,input().split())) for i in [0]*N]).T.astype(np.int64)
INF = 10**15

rx = C - x[::-1]
dx = np.zeros(N+2).astype(np.int64)
dx[N+1] = C
dx[1:-1] = x
dx = np.diff(dx)

cand = []


rv = v - dx[:-1]
rc = np.maximum.accumulate(np.cumsum(rv))
best = rc[-1]
cand.append(best)

lv = v[::-1] - dx[::-1][:-1]
lc = np.maximum.accumulate(np.cumsum(lv))
best = lc[-1]
cand.append(best)


first = (rc-x)[:-1] 
second = lc[:-1][::-1] 
if first.size:
    cand.append(np.max(first+second))

first = (lc-rx)[:-1]
second = rc[:-1][::-1]
if first.size:
    cand.append(np.max(first+second))

cand.append(0)
print(max(cand))

Solution (Python):

import sys
def input():
	return sys.stdin.readline().strip()

N, C = list(map(int, input().split()))
sushi = []
for i in range(N):
	sushi.append(tuple(map(int, input().split())))

sushi_sum = [0]
for i in range(N):
	sushi_sum.append(sushi_sum[-1] + sushi[i][1])


right_max = 0
right_list = []
left_max = 0
left_list = []
for i in range(N):
	if right_max < sushi_sum[i + 1] - sushi[i][0]:
		right_max = sushi_sum[i + 1] - sushi[i][0]
	right_list.append(sushi_sum[i + 1] - sushi[i][0])
	if left_max < sushi_sum[-1] - sushi_sum[i] - (C - sushi[i][0]):
		left_max = sushi_sum[-1] - sushi_sum[i] - (C - sushi[i][0])
	left_list.append(sushi_sum[-1] - sushi_sum[i] - (C - sushi[i][0]))

for i in range(1, N):
	right_list[i] = max(right_list[i - 1], right_list[i])
for i in range(N - 2, -1, -1):
	left_list[i] = max(left_list[i + 1], left_list[i])

right_left_max = 0
for i in range(N - 1):
	right_left_max = max(right_left_max, sushi_sum[i + 1] - 2*sushi[i][0] + left_list[i + 1])

left_right_max = 0
for i in range(1, N):
	left_right_max = max(left_right_max, sushi_sum[-1] - sushi_sum[i] - 2*(C - sushi[i][0]) + right_list[i - 1])

print(max(right_max, left_max, right_left_max, left_right_max))

Solution (Python):
from itertools import accumulate

N, C, *XV = map(int, open(0).read().split())

X = XV[::2]
V = XV[1::2]

A = [0] + list(accumulate(V))

ans = m0 = m1 = 0
for i in reversed(range(N)):
    a = A[i + 1] - X[i]
    ans = max(ans, a + m0, a - X[i] + m1)

    c = C - X[i]
    m = A[N] - A[i] - c
    m0 = max(m0, m - c)
    m1 = max(m1, m)

print(max(ans, m1))

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

def main():
    N,C = map(int, input().split())
    X = []
    for _ in range(N):
        X.append(list(map(int, input().split())))
    
    cw = [0] 
    ccw = [0] 
    for i in range(N):
        cw.append(cw[i] + X[i][1])
        ccw.append(ccw[i] + X[N-1-i][1])
    for i in range(N):
        cw[i+1] -= X[i][0]
        ccw[i+1] -= C - X[N-1-i][0]

    ma = 0
    ga = []
    for i in range(0, N+1):
        ma = max(ma, cw[i])
        ga.append(ma)
    ma = 0
    gb = []
    for i in range(0, N+1):
        ma = max(ma, ccw[i])
        gb.append(ma)

    ans = 0
    for bi in range(N+1):
        tmp = ccw[bi] + ga[N-bi]
        if bi > 0:
            tmp -= C - X[N-bi][0]
        ans = max(ans, tmp)

    for ai in range(N+1):
        tmp = cw[ai] + gb[N-ai]
        if ai > 0:
            tmp -= X[ai-1][0]
        ans = max(ans, tmp)

    print(ans)

if __name__ == '__main__':
    main()

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

cp = [0]*n
cp_rev = [0]*n
d = [0]*n

for i in range(n):
    x,v = map(int,input().split())
    d[i] = x
    cp[i] = v
    cp_rev[n-1-i] = v

sm = [0]*n
sm_rev = [0]*n
max_sm = [0]*n
max_sm_rev = [0]*n

sm[0] = cp[0] - d[0]
sm_rev[0] = cp_rev[0] - (c - d[n-1])
max_sm[0] = sm[0]
max_sm_rev[0] = sm_rev[0]

for i in range(1,n):
    sm[i] = sm[i-1] + cp[i] - d[i] + d[i-1]
    sm_rev[i] = sm_rev[i-1] + cp_rev[i] - (c - d[n-1-i]) + c - d[n-i]
    max_sm[i] = max(max_sm[i-1],sm[i])
    max_sm_rev[i] = max(max_sm_rev[i-1],sm_rev[i])

ret_ind = sm.index(max(sm))
ret_ind_rev = sm_rev.index(max(sm_rev)) 

ans = 0

for i in range(ret_ind + 1):
    ans = max(ans, sm[i])
    if n-i-2 >= 0:
        ans = max(ans, sm[i] - d[i] + max_sm_rev[n-i-2])

for i in range(ret_ind_rev + 1):
    ans = max(ans, sm_rev[i])
    if n-i-2 >= 0:
        ans = max(ans,sm_rev[i] - (c - d[n-1-i]) + max_sm[n-i-2])

print(ans)

Solution (Python):
from itertools import accumulate

N, C = map(int, input().split())
x, v = (
    zip(*(map(int, input().split()) for _ in range(N))) if N else
    ((), ())
)


acc_l = list(
    accumulate(
        (
            V - X
            for X, V in zip(
                [0] + [C - X for X in x[::-1]],
                accumulate((0,) + v[::-1])
            )
        ),
        max
    )
)
acc_r = list(
    accumulate(
        (
            V - X
            for X, V in zip(
                (0,) + x,
                accumulate((0,) + v)
            )
        ),
        max
    )
)


ans = max(
    max(
        V - 2 * X + acc_l[N - i]
        for i, X, V in zip(
            range(N + 1),
            (0,) + x,
            accumulate((0,) + v)
        )
    ),
    max(
        V - 2 * X + acc_r[N - i]
        for i, X, V in zip(
            range(N + 1),
            [0] + [C - X for X in x[::-1]],
            accumulate((0,) + v[::-1])
        )
    )
)

print(ans)

Solution (Python):


class SegmentTree:
    def __init__(self, L, op, ide):
        self.op = op
        self.ide = ide
        self.sz = len(L)
        self.n = 1
        self.s = 1
        for i in range(1000):
            self.n *= 2
            self.s += 1
            if self.n >= self.sz:
                break
        self.node = [self.ide]*(2*self.n-1)

        for i in range(self.sz):
            self.node[i+self.n-1] = L[i]

        for i in range(self.n-2,-1,-1):
            self.node[i] = self.op(self.node[i*2+1],self.node[i*2+2])
    
    def add(self, a, x):
        k = a+self.n-1
        self.node[k] += x
        for i in range(1000):
            k = (k-1)//2
            self.node[k] = self.op(self.node[2*k+1], self.node[2*k+2])
            if k <= 0:
                break
    
    def substitute(self, a, x):
        k = a+self.n-1
        self.node[k] = x
        for i in range(1000):
            k = (k-1)//2
            self.node[k] = self.op(self.node[2*k+1], self.node[2*k+2])
            if k <= 0:
                break

    def get_one(self, a):
        k = a+self.n-1
        return self.node[k]
    
    def get(self, l, r):
        res = self.ide
        n = self.n
        if self.sz <= r or 0 > l:
            print("ERROR: the indice are wrong.")
            return False

        for i in range(self.s):
            count = 2**i-1
            a = (r+1)//n
            b = (l-1)//n
            if a-b == 3:
                res = self.op(self.node[count+b+1],res)
                res = self.op(self.node[count+b+2],res)
                right = a*n
                left = (b+1)*n-1
                break
            if a-b == 2:
                res = self.op(self.node[count+b+1],res)
                right = a*n
                left = (b+1)*n-1
                break
            n = n//2

        
        n1 = n//2        
        for j in range(i+1,self.s):
            count = 2**j-1 
            a = (left+1)//n1
            b = (l-1)//n1
            if a-b == 2:
                res = self.op(self.node[count+b+1],res)
                left = (b+1)*n1-1                
            n1 = n1//2

        
        n1 = n//2        
        for j in range(i+1,self.s):
            count = 2**j-1 
            a = (r+1)//n1
            b = (right-1)//n1
            if a-b == 2:
                res = self.op(self.node[count+b+1],res)
                right = a*n1                
            n1 = n1//2
        return res

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

X = [list(map(int,input().split())) for i in range(N)]

R1 = [0]
R2 = [0]
r1,r2 = 0,0

prev = 0

for x in X:
    r1+=x[1]-(x[0]-prev)
    r2+=x[1]-2*(x[0]-prev)
    R1.append(r1)
    R2.append(r2)
    prev = x[0]

L1 = [0]
L2 = [0]
l1,l2 = 0,0

X = X[::-1]

prev = C

for x in X:
    l1+=x[1]-((C-x[0])-(C-prev))
    l2+=x[1]-2*((C-x[0])-(C-prev))
    L1.append(l1)
    L2.append(l2)
    prev = x[0]

STR1 = SegmentTree(R1,max,-10**27)
STR2 = SegmentTree(R2,max,-10**27)
STL1 = SegmentTree(L1,max,-10**27)
STL2 = SegmentTree(L2,max,-10**27)
max_score = 0
for i in range(N+1):
    max_score = max(STR1.get(0,N-i)+STL2.get(0,i),STR2.get(0,N-i)+STL1.get(0,i),max_score)

print(max_score)