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):
def main():
    n, c = map(int, input().split())
    sushi = [None]*n
    for i in range(n):
        sushi[i] = list(map(int, input().split()))
    cal_r = [None] * n
    cal_l = [None] * n
    max_r = [None] * n
    max_l = [None] * n
    cal_r[0] = sushi[0][1] - sushi[0][0]
    max_r[0] = cal_r[0]
    for i in range(1, n):
        cal_r[i] = cal_r[i-1] + sushi[i][1] - (sushi[i][0] - sushi[i-1][0])
        max_r[i] = max(max_r[i-1], cal_r[i])
    cal_l[n-1] = sushi[n-1][1] - (c - sushi[n-1][0])
    max_l[n-1] = cal_l[n-1]
    for i in reversed(range(n-1)):
        cal_l[i] = cal_l[i+1] + sushi[i][1] - (sushi[i+1][0] - sushi[i][0])
        max_l[i] = max(max_l[i+1], cal_l[i])
    max_r_1 = max(max_r)
    max_l_1 = max(max_l)
    ans = max(0, max_r_1, max_l_1)
    cal_r_2 = [None] * n
    cal_l_2 = [None] * n
    cal_r_2[n-1] = 0
    cal_l_2[0] = 0
    for i in range(n-1):
        cal_r_2[i] = cal_r[i] - sushi[i][0] + max_l[i+1]
    for i in reversed(range(1, n)):
        cal_l_2[i] = cal_l[i] - (c - sushi[i][0]) + max_r[i-1]
    max_r_2 = max(cal_r_2)
    max_l_2 = max(cal_l_2)
    ans = max(ans, max_l_2, max_r_2)
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):



from heapq import *






N,C=map(int,input().split())
XV=[list(map(int,input().split())) for i in range(N)]
XVR=list(reversed(XV))
value=0
tempvalue=0
csXV=[[0,0] for i in range(N)]
csXVR=[[0,0] for i in range(N)]
csXV[0][0]=XV[0][0]
csXV[0][1]=XV[0][1]
csXVR[0][0]=XV[-1][0]
csXVR[0][1]=XV[-1][1]
csXVR[0][0]=C-csXVR[0][0]
for i in range(1,N):
    csXV[i][0] =XV[i][0]
    csXV[i][1] =XV[i][1]+csXV[i-1][1]
    csXVR[i][0]=C-XV[N-1-i][0]
    csXVR[i][1]=XVR[i][1]+csXVR[i-1][1]


csXV[0].append(csXV[0][1]-csXV[0][0])
csXVR[0].append(csXVR[0][1]-csXVR[0][0])

for i in range(1,N):
    csXV[i].append(csXV[i][1]-csXV[i][0])
    csXVR[i].append(csXVR[i][1]-csXVR[i][0])

csXV[0].append(csXV[0][2])
csXVR[0].append(csXVR[0][2])



for i in range(1,N):
    csXV[i].append(max(csXV[i][2],csXV[i-1][3]))
    csXVR[i].append(max(csXVR[i][2],csXVR[i-1][3]))



value=0
for i in range(N-1):
    B=N-1 -i-1
    tempvalue=csXV[i][2]-csXV[i][0]+csXVR[B][3]
    value=max(tempvalue,value,csXV[i][3])

for i in range(N-1):
    B=N-1 -i-1
    tempvalue=csXVR[i][2]-csXVR[i][0]+csXV[B][3]
    value=max(tempvalue,value,csXV[i][3])

value=max(value,csXV[-1][3],csXVR[-1][3])

print(value)

Solution (Python):
import sys
input=sys.stdin.readline
import copy
N,C=map(int,input().split())
L=[]
for i in range(N):
    x,v=map(int,input().split())
    L.append([x,v])

LR=copy.deepcopy(L)
L=[[0,0]]+L

LR=LR[::-1]

for i in range(N):
    LR[i][0]=C-LR[i][0]
LR=[[0,0]]+LR

Lr=[0]
S=0
for i in range(1,N+1):
    S+=L[i][1]
    Lr.append(S-L[i][0])

LC=[0]

for i in range(1,N+1):
    LC.append(max(LC[-1],Lr[i]))


LRr=[0]
S=0
for i in range(1,N+1):
    S+=LR[i][1]
    LRr.append(S-LR[i][0])

LRC=[0]
for i in range(1,N+1):
    LRC.append(max(LRC[-1],LRr[i]))


ans=0
for i in range(N+1):
    cnt=LC[i]-L[i][0]+LRC[N-i]
    ans=max(ans,cnt)
for i in range(N+1):
    cnt=LRC[i]-LR[i][0]+LC[N-i]
    ans=max(ans,cnt)
print(ans)

Solution (Python):
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, C = lr()
XV = np.array([lr() for _ in range(N)])
Sushi = XV[:, 1]
Sushi_rev = Sushi[::-1]
dis = XV[:, 0]
dis_rev = C - dis[::-1]
Sushi_cum = Sushi.cumsum()
Sushi_rev_cum = Sushi_rev.cumsum()
Sushi_cum -= dis
Sushi_rev_cum -= dis_rev
Sushi_max = np.maximum.accumulate(Sushi_cum)
Sushi_max_rev = np.maximum.accumulate(Sushi_rev_cum)
answer = max(0, Sushi_max[-1], Sushi_max_rev[-1])

for i in range(N-1):
    cal = Sushi_cum[i] - dis[i] + Sushi_max_rev[N-2-i]
    cal2 = Sushi_rev_cum[i] - dis_rev[i] + Sushi_max[N-2-i]
    cal = max(cal, cal2)
    if cal > answer:
        answer = cal

print(answer)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

INF = -(2 ** 31)

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


def spam():
    L = [0] * N
    pre = 0
    pre_max = -(2 ** 31)
    for i in range(N):
        x, v = X[-i - 1]
        L[i] = max(pre_max, pre + v - (C - x))
        pre += v
        pre_max = L[i]

    ans = max(pre_max, 0)
    pre = 0
    for i in range(N):
        x, v = X[i]
        tmp = pre + v - x

        if i < N - 1:
            tmp2 = max(L[N - i - 2] - x, 0)
        else:
            tmp2 = 0
        ans = max(ans, tmp + tmp2)
        pre += v
    return ans


def main():
    global X
    ans = spam()
    X = X[::-1]
    for i in range(N):
        X[i][0] = C - X[i][0]
    ans = max(ans, spam())
    print(ans)


main()

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

def main():
    N,C = map(int,input().split())
    susi = [tuple(map(int,input().split())) for _ in range(N)]
    csusi = list(reversed(susi))
    
    cal,ccal = 0,0
    now,cnow = 0,0
    eat,ceat = [(0,0)],[(0,0)]
    for i,j in zip(susi,csusi):
        x,v = i
        cal += v
        if cal-x > eat[-1][0]:
            now = x
            eat.append((cal-x,now))
        else:
            eat.append((eat[-1][0],now))
        cx,cv = j
        ccal += cv
        if ccal-(C-cx) > ceat[-1][0]:
            cnow = C-cx
            ceat.append((ccal-(C-cx),cnow))
        else:
            ceat.append((ceat[-1][0],cnow))
    
    ceat.reverse()
    ans = 0
    for i,j in zip(eat,ceat):
        eat,x = i
        ceat,cx = j
        ans = max(ans,eat+ceat-min(x,cx))

    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
n,c = map(int,input().split())
sushi = []
for _ in range(n):
  sushi.append(list(map(int,input().split())))
can = []

right1 = []
right2 = []
tmp = 0
for i in range(n):
  s,v = sushi[i]
  tmp += v
  right1.append([tmp-s,s])
  right2.append([tmp-2*s,s])
left1 = []
left2 = []
tmp = 0
for i in range(n)[::-1]:
  s,v = sushi[i]
  tmp += v
  left1.append([tmp-(c-s),c-s])
  left2.append([tmp-2*(c-s),c-s])
right1.sort()
left1.sort()



can.append(0)
can.append(right1[-1][0])
can.append(left1[-1][0])

for i in range(n):
  energy,s = right2[i]
  while left1[-1][1] + s >= c:
    left1.pop()
    if left1 == []:
      break
  else:
    can.append(energy + left1[-1][0])
    
    continue
  break

for i in range(n):
  energy,s = left2[i]
  while right1[-1][1] + s >= c:
    right1.pop()
    if right1 == []:
      break
  else:
    can.append(energy + right1[-1][0])
    
    continue
  break
print(max(can))

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

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

for i in range(N):
    xv[i][0],xv[i][1]=map(int,input().split())
    
xv.sort()

S=[0]*(N+1)
ans=0
r=[0]*N
l=[0]*N

ma=0
ma_i=0
for i in range(N):
    S[i+1]=S[i]+xv[i][1]
    a=S[i+1]-xv[i][0]
    if a>ma:
        ma=a
        ma_i=i
    r[i]=ma_i
        
        
ma=0
ma_i=N-1      
for i in range(N):
    a=(S[-1]-S[N-i-1])-(C-xv[N-i-1][0])
    if a>ma:
        ma=a
        ma_i=N-i-1
    l[N-i-1]=ma_i
    
    
for i in range(N):
    temp1=S[i+1]-xv[i][0]
    temp2=temp1-xv[i][0]
    if i!=N-1:
        temp2+=(S[-1]-S[l[i+1]]) - (C-xv[l[i+1]][0])
    ans=max(ans,temp1,temp2)
      

for i in range(N):
    temp1=(S[-1]-S[i])-(C-xv[i][0])
    temp2=temp1-(C-xv[i][0])
    if i!=0:
        temp2+=S[r[i-1]+1] -xv[r[i-1]][0]
    ans=max(ans,temp1,temp2)
    
    
print(ans)

Solution (Python):
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True  and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,c = inm()
x = []
v = []
for i in range(n):
    xx,vv = inm()
    x.append(xx)
    v.append(vv)
l1 = [0]*n
l2 = [0]*n
r1 = [0]*n
r2 = [0]*n
acc = 0
for i in range(n):
    acc += v[i]
    l1[i] = max(l1[i-1], acc-x[i])
    l2[i] = max(l2[i-1], acc-2*x[i])
acc = 0
for i in range(n-1,-1,-1):
    acc += v[i]
    r1[i] = max(r1[(i+1)%n], acc-(c-x[i]))
    r2[i] = max(r2[(i+1)%n], acc-2*(c-x[i]))

ddprint(l1)
ddprint(l2)
ddprint(r1)
ddprint(r2)
mx = 0
for i in range(n):
    mx = max([mx, l1[i]+(r2[i+1] if i<n-1 else 0), \
                  r1[i]+(l2[i-1] if i>0 else 0)])
print(mx)

Solution (Python):
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue


Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): 
    n,c = map(int,input().split())
    xv = [list(map(int,input().split())) for i in range(n)]
    x = [xv[i][0] for i in range(n)]
    v = [xv[i][1] for i in range(n)]
    r1,r2,l1,l2 = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
    ans = 0
    dis = 0
    for i in range(n):
        r1[i+1] = r1[i]+v[i]-(x[i]-dis)
        r2[i+1] = r2[i]+v[i]-2*(x[i]-dis)
        dis = x[i]
    dis = c
    for i in reversed(range(n)):
        l1[n-i] = l1[n-i-1]+v[i]-(dis-x[i])
        l2[n-i] = l2[n-i-1]+v[i]-2*(dis-x[i])
        dis = x[i]
    for i in range(n):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(n+1):
        ans = max(ans,max(r2[i]+l1[n-i],l2[i]+r1[n-i]))
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue


Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): 
    n,c = map(int,input().split())
    xv = [list(map(int,input().split())) for i in range(n)]
    x = [xv[i][0] for i in range(n)]
    v = [xv[i][1] for i in range(n)]
    r1,r2,l1,l2 = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
    ans = 0
    dis = 0
    for i in range(n):
        r1[i+1] = r1[i]+v[i]-(x[i]-dis)
        r2[i+1] = r2[i]+v[i]-2*(x[i]-dis)
        dis = x[i]
    dis = c
    for i in reversed(range(n)):
        l1[n-i] = l1[n-i-1]+v[i]-(dis-x[i])
        l2[n-i] = l2[n-i-1]+v[i]-2*(dis-x[i])
        dis = x[i]
    for i in range(n):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(n+1):
        ans = max(ans,max(r2[i]+l1[n-i],l2[i]+r1[n-i]))
    print(ans)
if __name__ == "__main__":
    main()

Solution (Python):
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue


Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): 
    n,c = map(int,input().split())
    xv = [list(map(int,input().split())) for i in range(n)]
    x = [xv[i][0] for i in range(n)]
    v = [xv[i][1] for i in range(n)]
    r1,r2,l1,l2 = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
    ans = 0
    dis = 0
    for i in range(n):
        r1[i+1] = r1[i]+v[i]-(x[i]-dis)
        r2[i+1] = r2[i]+v[i]-2*(x[i]-dis)
        dis = x[i]
    dis = c
    for i in reversed(range(n)):
        l1[n-i] = l1[n-i-1]+v[i]-(dis-x[i])
        l2[n-i] = l2[n-i-1]+v[i]-2*(dis-x[i])
        dis = x[i]
    for i in range(n):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(n+1):
        subans = max(r2[i]+l1[n-i],l2[i]+r1[n-i])
        ans = max(ans,subans)
    print(ans)
if __name__ == "__main__":
    main()

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







best_sushi_noturn=[0]*(N+1) 
best_sushi_turn=[0]*(N+1) 
bestval_noturn=0 
bestval_turn=0 
valsum=0 
for i in range(1,N+1):
  
  
  
  dist=C-X[N-i]
  valsum+=V[N-i]
  if valsum-dist>bestval_noturn:
    bestval_noturn=valsum-dist
    best_sushi_noturn[i]=bestval_noturn
  else:
    best_sushi_noturn[i]=best_sushi_noturn[i-1] 
  if valsum-dist*2>bestval_turn:
    bestval_turn=valsum-dist*2
    best_sushi_turn[i]=bestval_turn
  else:
    best_sushi_turn[i]=best_sushi_turn[i-1] 


valsum=0

ans=best_sushi_noturn[N]
for i in range(N):
  valsum+=V[i]
  cost=X[i]
  
  if valsum-cost*2+best_sushi_noturn[N-(i+1)]>ans:
    ans=valsum-cost*2+best_sushi_noturn[N-(i+1)]
  
  if valsum-cost+best_sushi_turn[N-(i+1)]>ans:
    ans=valsum-cost+best_sushi_turn[N-(i+1)]

print(ans)

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

N, C = map(int, input().split())
x = [0] * N
v = [0] * N
for i in range(N):
    x[i], v[i] = map(int, input().split())
clockwise = list(accumulate(v))
counterclockwise = list(accumulate(v[::-1]))[::-1]
for i in range(N):
    clockwise[i] -= x[i]
    counterclockwise[i] -= C-x[i]
clockwise_max = [0] * N
for i in range(1, N):
    clockwise_max[i] = max(clockwise_max[i-1], clockwise[i-1])
counterclockwise_max = [0] * N
for i in range(N-1)[::-1]:
    counterclockwise_max[i] = max(counterclockwise_max[i+1], counterclockwise[i+1])
ans = 0
for i in range(N):
    ans = max(ans, clockwise[i])
    ans = max(ans, clockwise[i]-x[i]+counterclockwise_max[i])
for i in range(N)[::-1]:
    ans = max(ans, counterclockwise[i])
    ans = max(ans, counterclockwise[i]-(C-x[i])+clockwise_max[i])
print(ans)

Solution (Python):
n,c=map(int, input().split())
a = [[0,0]]+[list(map(int, input().split())) for i in range(n)]
l=[[0,0] for i in range(n+1)]
r=[[0,0] for i in range(n+1)]
b = 0
b1 = 0

x=[0]*(n+1)
y=[0]*(n+1)
ans=0
ansl=0
ansr=0


ans1=-10**20
ans2=-10**20
for i in range(n+1):
    b+=a[i][1]
    l[i][0]=a[i][0]
    l[i][1]=b
    if b-l[i][0]>ans1:
        ans1=b-a[i][0]
        x[i]=ans1
    else:
        x[i]=x[i-1]

for i in range(n+1):
    b1+=a[-i][1]
    r[i][0]=c-a[-i][0]
    r[i][1]=b1
    if b1-r[i][0]>ans2:
        ans2=b1-r[i][0]
        y[i]=ans2
    else:
        y[i]=y[i-1]
r[0][0]=0
y[0]=0



for i in range(n):
    cnt=x[n-i]+r[i][1]-2*r[i][0]
    ansr=max(cnt,ansr)


for i in range(n):
    cnt=y[n-i]+l[i][1]-2*l[i][0]
    ansl=max(cnt,ansl)
print(max(ansr,ansl))

Solution (Python):
N,C = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]
A.insert(0,[0,0])

F = [0 for _ in range(N+1)]
F[N] = A[N][1]-(C-A[N][0])
for i in range(N-1,0,-1):
    F[i] = F[i+1]+A[i][1]-(A[i+1][0]-A[i][0])
G = [0 for _ in range(N+1)]
for i in range(1,N+1):
    G[i] = G[i-1]+A[i][1]-(A[i][0]-A[i-1][0])
cmax = max(max(F),max(G))
dmax = 0
for i in range(N-1,0,-1):
    dmax = max(dmax,F[i+1])
    cmax = max(cmax,dmax+G[i]-A[i][0])
emax = 0
for i in range(2,N+1):
    emax = max(emax,G[i-1])
    cmax = max(cmax,emax+F[i]-(C-A[i][0]))
print(cmax)

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


right = [[0,0]]
for i in range(n):
    right.append([xv[i][0],right[-1][1]+xv[i][1]])

right_best =[0]
for i in range(1,len(right)):
    right_best.append(max(right[i][1]-right[i][0],right_best[-1]))

right_return_best = [0]
for i in range(1,len(right)):
    right_return_best.append(max(right[i][1]-right[i][0]*2,right_return_best[-1]))



for i in range(n):
    xv[i][0]=c-xv[i][0]
xv.reverse()

left = [[0,0]]
for i in range(n):
    left.append([xv[i][0],left[-1][1]+xv[i][1]])

left_best =[0]
for i in range(1,len(left)):
    left_best.append(max(left[i][1]-left[i][0],left_best[-1]))

left_return_best = [0]
for i in range(1,len(left)):
    left_return_best.append(max(left[i][1]-left[i][0]*2,left_return_best[-1]))



ans = 0
for i in range(n+1):
    ans = max(ans,left_best[i]+right_return_best[n-i], right_best[i]+left_return_best[n-i])

print(ans)

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

right = [0]*N
right[0] = L[0][1] - L[0][0]
for i in range(N-1):
    right[i+1] = right[i] + L[i+1][1] - (L[i+1][0] - L[i][0])

left = [0]*N
left[N-1] = L[N-1][1] - (C - L[N-1][0])
for i in range(N-1, 0, -1):
    left[i-1] = left[i] + L[i-1][1] - (L[i][0] - L[i-1][0])

Right = [0]*(N+1)
for i in range(N):
    Right[i+1] = max(right[i], Right[i])
Left = [0]*(N+1)
for i in range(N, 0, -1):
    Left[i-1] = max(left[i-1], Left[i])

ans = max(0, max(right), max(left))
for i in range(N-1, -1, -1):
    ans = max(ans, Right[i] + left[i] - (C - L[i][0]))
for i in range(N):
    ans = max(ans, Left[i+1] + right[i] - L[i][0])

print(ans)

Solution (Python):
n,c = map(int, input().split())
s = [tuple(map(int, input().split())) for _ in range(n)]
lx = [0] + [x[0] for x in s]
rx = [0] + [c-x[0] for x in s[::-1]]
lv = [0] + [x[1] for x in s]
rv = [0] + [x[1] for x in s[::-1]]
lg = [0]*(n+1)
rg = [0]*(n+1)
for i in range(1,n+1):
  lv[i] += lv[i-1]
  rv[i] += rv[i-1]
  lg[i] = lv[i] - lx[i]
  rg[i] = rv[i] - rx[i]
  if lg[i] < lg[i-1]: lg[i] = lg[i-1]
  if rg[i] < rg[i-1]: rg[i] = rg[i-1]

ans = 0
for i in range(n+1):
  ls = lg[i] + rg[n-i] - lx[i]
  rs = rg[i] + lg[n-i] - rx[i]
  if ls > ans: ans = ls
  if rs > ans: ans = rs
print(ans)

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

R = [(0,0)]
L = [(0,0)]

for s in sushi:
    R.append((s[0],R[-1][1]+s[1]))

for s in sushi[::-1]:
    L.append((C-s[0],L[-1][1]+s[1]))

R_reversible = [False for _ in range(N+1)]
L_reversible = [False for _ in range(N+1)]

for i in range(N+1):
    if R[i][1]-2*R[i][0] >= 0:
        R_reversible[i] = True
    if L[i][1]-2*L[i][0] >= 0:
        L_reversible[i] = True
        
R_dif = [0 for _ in range(N+1)]
L_dif = [0 for _ in range(N+1)]

for i in range(N+1):
    R_dif[i] = R[i][1]-R[i][0]
    L_dif[i] = L[i][1]-L[i][0]
    
rmax = 0
lmax = 0

for i in range(N+1):
    if rmax > R_dif[i]:
        R_dif[i] = rmax
    if lmax > L_dif[i]:
        L_dif[i] = lmax
    rmax = max(rmax,R_dif[i])
    lmax = max(lmax,L_dif[i])
    
ans = max(rmax,lmax)

for i in range(1,N+1):
    if R_reversible[i]:
        ans = max(ans,R[i][1]-2*R[i][0]+L_dif[N-i])
    if L_reversible[i]:
        ans = max(ans,L[i][1]-2*L[i][0]+R_dif[N-i])

print(ans)

Solution (Python):
n,c=map(int,input().split())
L=R=Rmax=0
x=[0]*n
v=[0]*n
for i in range(n):
  xx,vv=map(int,input().split())
  x[i]=xx
  v[i]=vv
  L+=vv
ans=L-x[-1]
for i in reversed(range(n)):
  L-=v[i]
  R+=v[i]
  Rmax=max(Rmax,R-(c-x[i]))
  ans=max(ans,L-(x[i-1]*2 if i>0 else 0)+Rmax)
Lmax=0
for i in range(n):
  L+=v[i]
  R-=v[i]
  Lmax=max(Lmax,L-x[i])
  ans=max(ans,R-((c-x[i+1])*2 if i<n-1 else 0)+Lmax)
print(ans)

Solution (Python):
def main():
    from collections import namedtuple

    Dish = namedtuple('Dish', 'idx x v')

    n, c = map(int, input().split())

    ds = []
    for i in range(n):
        x, v = map(int, input().split())
        ds.append(Dish(idx=i, x=x, v=v))

    gol = [0] * n  
    s = 0
    ma = 0
    for d in ds:
        s += d.v
        ma = max(ma, s - d.x)
        gol[d.idx] = ma

    gor = [0] * n  
    s = 0
    ma = 0
    for d in reversed(ds):
        s += d.v
        ma = max(ma, s - (c - d.x))
        gor[d.idx] = ma

    gol0 = [0] * n  
    for d in reversed(ds):
        gol0[d.idx] = gol[d.idx] - d.x

    gor0 = [0] * n  
    for d in reversed(ds):
        gor0[d.idx] = gor[d.idx] - (c - d.x)

    ret = max(max(gol), max(gor))
    for l in range(n - 1):
        t = gol0[l] + gor[l + 1]
        ret = max(ret, t)

    for r in range(n - 1, 0, -1):
        t = gor0[r] + gol[r - 1]
        ret = max(ret, t)

    print(ret)


if __name__ == '__main__':
    main()

Solution (Python):
from itertools import accumulate
from operator import sub
N, C = map(int, input().split())
X, V = map(list, zip(*[tuple(map(int, input().split())) for _ in range(N)]))
VA = list(accumulate([0]+V))
VR = list(accumulate([0]+V[::-1]))
XR = [0]+list(map(lambda x:C-x, X[::-1]))
X = [0]+X
VA = list(accumulate(map(sub, VA, X), max))
VR = list(accumulate(map(sub, VR, XR), max))
print(max(VA[i]+VR[N-i]-min(X[i], XR[N-i]) for i in range(N+1)))

Solution (Python):
from bisect import bisect_left
def main():
    n,c = map(int,input().split())
    xv = [tuple(map(int,input().split())) for _ in range(n)]
    xvr = []
    for i in range(n):
        j = n-i-1
        xvr.append((c-xv[j][0],xv[j][1]))
    xvv = [0]*n
    xvv[0] = xv[0]
    for i in range(1,n):
        xvv[i] = (xv[i][0],xvv[i-1][1]+xv[i][1])
    xvrv = [0]*n
    xvrv[0] = xvr[0]
    for i in range(1,n):
        xvrv[i] = (xvr[i][0],xvrv[i-1][1]+xvr[i][1])
    xvm = [(0,0)]
    xvmi = [0]
    for i in xvv:
        j = xvm[-1]
        if i[1]-i[0] >= j[1]-j[0]:
            xvm.append(tuple(i))
            xvmi.append(i[0])
    xvrm = [(0,0)]
    xvrmi = [0]
    for i in xvrv:
        j = xvrm[-1]
        if i[1]-i[0] >= j[1]-j[0]:
            xvrm.append(tuple(i))
            xvrmi.append(i[0])
    ans = max([xvm[-1][1]-xvm[-1][0],xvrm[-1][1]-xvrm[-1][0]])
    for i in xvm:
        t = c-i[0]
        idx = bisect_left(xvrmi,t)-1
        tans = xvrm[idx][1]-xvrm[idx][0]+i[1]-i[0]*2
        if tans > ans:
            ans = tans
    for i in xvrm:
        t = c-i[0]
        idx = bisect_left(xvmi,t)-1
        tans = xvm[idx][1]-xvm[idx][0]+i[1]-i[0]*2
        if tans > ans:
            ans = tans
    print(ans)
    
if __name__ == '__main__':
    main()

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

ans, value = 0, 0
for i in L:
    cost = i[0]
    value += i[1]
    ans = max(ans, value - cost)

value = 0
for i in L[::-1]:
    cost = C - i[0]
    value += i[1]
    ans = max(ans, value - cost)

rList = [0] * (N + 1)
value = 0
for i in range(N):
    sushi = L[i]
    cost = sushi[0]
    value += sushi[1]
    rList[i + 1] = max(rList[i], value - cost)

lList = [0] * (N + 1)
value = 0
for i in range(N):
    sushi = L[-1-i]
    cost = C - sushi[0]
    value += sushi[1]
    lList[i + 1] = max(lList[i], value - cost)

value = 0
for i in range(N):
    sushi = L[i]
    cost = sushi[0]
    value += sushi[1]
    ans = max(ans, value - cost * 2 + lList[N - (i + 1)])

value = 0
for i in range(N):
    sushi = L[-1-i]
    cost = C - sushi[0]
    value += sushi[1]
    ans = max(ans, value - cost * 2 + rList[N - (i + 1)])

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N,C=map(int,input().split())
x=[]
v=[0]
for i in range(N):
    xx,vv=map(int,input().split())
    x.append(xx)
    v.append(v[i]+vv)

cw=[0]
for i in range(N):
    cw.append(max(cw[i],v[i+1]-x[i]))

ccw=[0]
for i in range(N):
    ccw.append(max(ccw[i],v[N]-v[N-i-1]-(C-x[-i-1])))

cw_ccw=0
for i in range(N-1):
    cw_ccw=max(cw_ccw,v[i+1]-x[i]*2+ccw[N-i-1])

ccw_cw=0
for i in range(N-1):
    ccw_cw=max(ccw_cw,v[N]-v[N-i-1]-(C-x[-i-1])*2+cw[N-i-1])


print(max(cw+ccw+list([cw_ccw,ccw_cw])))

Solution (Python):
from itertools import accumulate

N, C  = map(int, input().split())
x_cw = []   
x_acw = []  
v_cw = []     
for i in range(N):
    x,v = map(int, input().split())
    x_cw.append(x)
    v_cw.append(v)
v_acw = v_cw[::-1]
x_acw = [C - x for x in x_cw[::-1]]
x_cw = [0] + x_cw
x_acw = [0] + x_acw


v_cw1 = [v_cw[i]-(x_cw[i+1]-x_cw[i]) for i in range(N)]        
v_cw2 = [v_cw[i]-2*(x_cw[i+1]-x_cw[i]) for i in range(N)]     
v_acw1 = [v_acw[i]-(x_acw[i+1]-x_acw[i]) for i in range(N)]        
v_acw2 = [v_acw[i]-2*(x_acw[i+1]-x_acw[i]) for i in range(N)]     

acc_cw1 = list(accumulate(v_cw1))
acc_acw1 = list(accumulate(v_acw1))
acc_cw2 = list(accumulate(v_cw2))
acc_acw2 = list(accumulate(v_acw2))

acc_acw1 = acc_acw1[::-1]
acc_cw1 = acc_cw1[::-1]


max_cw2 = []
m = 0

for c in acc_cw2:
    m = max(c,m)
    max_cw2.append(m)
ans_cw = acc_acw1[0] 
for i in range(1,N):
    ans_cw = max(ans_cw, max_cw2[i-1]+acc_acw1[i])


m = 0
max_acw2 = []
for c in acc_acw2:
    m = max(c, m)
    max_acw2.append(m)
ans_acw = acc_cw1[0] 
for i in range(1,N):
    ans_acw = max(ans_acw, max_acw2[i-1]+acc_cw1[i])
ans = max(ans_acw,ans_cw)
print(max(0,ans))