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):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
from collections import deque
def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math
import bisect
from logging import getLogger, StreamHandler, DEBUG, WARNING
logger = getLogger(__name__)
handler = StreamHandler()
handler.setLevel(DEBUG)
logger.setLevel(DEBUG)
handler.setLevel(WARNING)
logger.setLevel(WARNING)
logger.addHandler(handler)
logger.propagate = False











def main():
    n, m = getList()
    sushis = []
    for i in range(n):
        sushis.append(getList())

    tmp = 0
    acc = [(0, 0)]
    acc2 = [0]
    acc2idx = [0]

    for sushi in sushis:
        tmp += sushi[1]
        if tmp - sushi[0] > acc[-1][1]:
            acc.append((sushi[0], tmp - sushi[0]))
        if tmp - 2 * sushi[0] > acc2[-1]:
            acc2.append(tmp - sushi[0] * 2)
            acc2idx.append(sushi[0])

    tmp = 0
    racc = [(0, 0)]
    racc2 = [0]
    racc2idx = [0]

    for sushi in sushis[::-1]:
        tmp += sushi[1]
        dist = m - sushi[0]
        if tmp - dist > racc[-1][1]:
            racc.append((sushi[0], tmp - dist))
        if tmp - 2 * dist > racc2[-1]:
            racc2.append(tmp - 2 * dist)
            racc2idx.append(dist)


    ans = 0
    for asu in acc:
        tmp = asu[1]
        idx = bisect.bisect_left(racc2idx, m - asu[0])
        tmp += racc2[idx - 1]
        if tmp > ans:
            ans = tmp
            logger.info(asu, tmp, idx)

    for asu in racc:
        tmp = asu[1]
        idx = bisect.bisect_left(acc2idx, asu[0])
        tmp += acc2[idx - 1]
        if tmp > ans:
            ans = tmp
            logger.info(asu, tmp)

    print(ans)
    logger.info(acc, acc2)
    logger.info(racc, racc2, racc2idx)

    return
if __name__ == "__main__":
    main()

Solution (Python):

import sys
input = sys.stdin.buffer.readline


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


def main():
	N, C = getlist()
	left1sum = [0]
	right1sum = [0]
	left2sum = [0]
	right2sum = [0]
	X = []
	V = []
	for i in range(N):
		x, v = getlist()
		X.append(x)
		V.append(v)
	for i in range(N):
		left1sum.append(left1sum[-1] + V[-1 - i])
		left2sum.append(left2sum[-1] + V[-1 - i])
		right1sum.append(right1sum[-1] + V[i])
		right2sum.append(right2sum[-1] + V[i])
	
	
	
	
	for i in range(N):
		right1sum[i + 1] -= X[i]
		right2sum[i + 1] -= 2 * X[i]
		left1sum[i + 1] -= C - X[-1 - i]
		left2sum[i + 1] -= 2 * (C - X[-1 - i])

	for i in range(N):
		right1sum[i + 1] = max(right1sum[i + 1], right1sum[i])
		right2sum[i + 1] = max(right2sum[i + 1], right2sum[i])
		left1sum[i + 1] = max(left1sum[i + 1], left1sum[i])
		left2sum[i + 1] = max(left2sum[i + 1], left2sum[i])
	
	
	
	
	ans = 0
	for i in range(N + 1):
		ans = max(ans, right1sum[i] + left2sum[N - i])
		ans = max(ans, right2sum[i] + left1sum[N - i])
	print(ans)

if __name__ == '__main__':
	main()

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

l=[0]*N
l[0]=xv[0][1]
for i in range(1,N):
  l[i]=l[i-1]+xv[i][1]
for i in range(N):
  l[i]-=xv[i][0]

r=[0]*N
r[0]=xv[N-1][1]
for i in reversed(range(N-1)):
  r[N-1-i]=r[N-1-i-1]+xv[i][1]
for i in reversed(range(N)):
  r[N-1-i]-=C-xv[i][0]
  
ans=max(max(l),max(r))

lm=[0]*N
lm[0]=l[0]
for i in range(1,N):
  lm[i]=max(lm[i-1],l[i])
  
rm=[0]*N
rm[0]=r[0]
for i in range(1,N):
  rm[i]=max(rm[i-1],r[i])

for i in range(N-1):
  ans=max(ans,l[i]-xv[i][0]+rm[N-1-i-1])
for i in range(N-1):
  ans=max(ans,r[i]-C+xv[N-1-i][0]+lm[N-1-i-1])
  
print(max(ans,0))

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    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())

    revX=[c-x for x in X]
    revV=V[:]

    for i in range(n-1):
        V[i+1]+=V[i]
    for i in range(n):
        V[i]-=X[i]

    maxV=V[:]
    for i in range(n-1):
        maxV[i+1]=max(maxV[i+1],maxV[i])


    for i in range(n-1,0,-1):
        revV[i-1]+=revV[i]
    for i in range(n-1,-1,-1):
        revV[i]-=revX[i]

    maxrevV=revV[:]
    for i in range(n-1,0,-1):
        maxrevV[i-1]=max(maxrevV[i-1],maxrevV[i])

    
    ans=max(max(maxV),max(maxrevV),0)

    
    for i in range(n-1):
        ans=max(ans,V[i]+maxrevV[i+1]-X[i])

    
    for i in range(1,n):
        ans=max(ans,revV[i]+maxV[i-1]-revX[i])

    print(ans)
resolve()

Solution (Python):
def main():
    from itertools import accumulate as ac
    n,c=map(int,input().split())
    xv=[list(map(int,input().split())) for _ in [0]*n]
    rmemo=[0]*n
    lmemo=[0]*n
    rmemo[0]=xv[0][1]-xv[0][0]
    lmemo[n-1]=xv[n-1][1]-(c-xv[n-1][0])
    for i in range(1,n):
        rmemo[i]=rmemo[i-1]+xv[i][1]-xv[i][0]+xv[i-1][0]
    for i in range(n-2,-1,-1):
        lmemo[i]=lmemo[i+1]+xv[i][1]+xv[i][0]-xv[i+1][0]
    temp=rmemo[0]
    rmemo2=[temp]*(n)
    temp=lmemo[-1]
    lmemo2=[temp]*(n+1)
    lmemo2[-1]=0
    for i in range(1,n):
        rmemo2[i]=max(rmemo[i],rmemo2[i-1])
    for i in range(n-2,-1,-1):
        lmemo2[i]=max(lmemo[i],lmemo2[i+1])
    rmemo2=[0]+rmemo2
    ans=max(rmemo+lmemo+[0])
    for i in range(n):
        ans=max(ans,rmemo[i]+lmemo2[i+1]-xv[i][0])
        ans=max(ans,lmemo[i]+rmemo2[i]+xv[i][0]-c)
    print(ans)
main()

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

A = [0] * (N+1)
B = [0] * (N+1)
MAA = [0] * (N+1)
MAB = [0] * (N+1)

for i in range(N):
    A[i+1] = A[i] + X[i][0] - (X[i][1] - (X[i-1][1] if i else 0))
    MAA[i+1] = max(MAA[i], A[i+1])

for i in range(N)[::-1]:
    B[i] = B[i+1] + X[i][0] + (X[i][1] - (X[i+1][1] if i < N-1 else C))
    MAB[i] = max(MAB[i+1], B[i])

ma = max(max(MAA), max(MAB))
for i in range(N):
    ma = max(ma, A[i+1] + MAB[i+1] - X[i][1])
    ma = max(ma, B[i] + MAA[i] + X[i][1] - C)

print(ma)

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

N, C = map(int, readline().split())
xv = np.array(read().split(), np.int64).reshape(N, 2)
v = xv[:, 1]
x = xv[:, 0]

ax = C - x[::-1]
cx = x.copy()
cx[1:] = cx[1:] - cx[:-1]
acx = C - x
acx[:-1] = acx[:-1] - acx[1:]

clockwise = np.cumsum(v - cx)
anticlockwise = v - acx
anticlockwise = np.cumsum(anticlockwise[::-1])

con_max = np.maximum.accumulate(clockwise)
anti_max = np.maximum.accumulate(anticlockwise)

answer = [0, con_max[-1], anti_max[-1]]

clockwise = clockwise - x
anti_max = anti_max[::-1]
clockwise[:-1] = clockwise[:-1] + anti_max[1:]
anticlockwise = anticlockwise - ax
con_max = con_max[::-1]
anticlockwise[:-1] = anticlockwise[:-1] + con_max[1:]

answer.append(anticlockwise.max())
answer.append(clockwise.max())

print(max(answer))

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

N, C = map(int, readline().split())
xv = np.array(read().split(), np.int64).reshape(N, 2)
v = xv[:, 1]
x = xv[:, 0]

ax = C - x[::-1]
cx = x.copy()
cx[1:] = cx[1:] - cx[:-1]
acx = C - x
acx[:-1] = acx[:-1] - acx[1:]

clockwise = v - cx
np.cumsum(clockwise, out=clockwise)
anticlockwise = v - acx
anticlockwise = np.cumsum(anticlockwise[::-1])

con_max = np.maximum.accumulate(clockwise)
anti_max = np.maximum.accumulate(anticlockwise)

answer = [0, con_max[-1], anti_max[-1]]

for i in range(N - 1):
    answer.append(clockwise[i] - x[i] + anti_max[N - i - 2])
    answer.append(anticlockwise[i] - ax[i] + con_max[N - i - 2])

print(max(answer))

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]
inf=float("inf")
n,c=map(int,input().split())
xv=[list(map(int,input().split())) for i in range(n)]

ra=[0]*(n+1)
ra[1]=xv[0][1]-xv[0][0]
for i in range(1,n):
    ra[i+1]=ra[i]+xv[i][1]-(xv[i][0]-xv[i-1][0])
mra=[0]*(n+1)
mra[1]=ra[1]
for i in range(1,n):
    mra[i+1]=max(mra[i],ra[i+1])



lb=[0]*(n+1)
lb[1]=xv[-1][1]-(c-xv[-1][0])
for i in range(1,n):
    lb[i+1]=lb[i]+xv[-1-i][1]-(xv[-i][0]-xv[-1-i][0])
mlb=[0]*(n+1)
mlb[1]=lb[1]
for i in range(1,n):
    mlb[i+1]=max(mlb[i],lb[i+1])



ans=max(0,lb[0]+mra[n])
for i in range(1,n+1):
    ans=max(ans,lb[i]+mra[n-i]-(c-xv[-i][0]))
ans=max(ans,ra[0]+mlb[n])
for i in range(1,n+1):
    ans=max(ans,ra[i]+mlb[n-i]-xv[i-1][0])
print(ans)

Solution (Python):
n,c=map(int,input().split())
xy=[list(map(int,input().split())) for i in range(n)]
data=[0]*(n+1)
for i in range(n):
    x,y=xy[i]
    data[i+1]=data[i]+y
data1=[0]*(n+1)
data2=[0]*(n+1)
for i in range(n):
    x,y=xy[i]
    data1[i+1]=data[i+1]-x
    data2[i+1]=data[i+1]-2*x
data=[0]*(n+1)
for i in range(n):
    x,y=xy[n-1-i]
    data[i+1]=data[i]+y
data3=[0]*(n+1)
data4=[0]*(n+1)
for i in range(n):
    x,y=xy[n-1-i]
    data3[i+1]=data[i+1]-(c-x)
    data4[i+1]=data[i+1]-2*(c-x)
for i in range(1,n+1):
    data1[i]=max(data1[i],data1[i-1])
    data2[i]=max(data2[i],data2[i-1])
    data3[i]=max(data3[i],data3[i-1])
    data4[i]=max(data4[i],data4[i-1])
ans=-float("inf")
for i in range(0,n+1):
    a=data2[i]+data3[n-i]
    b=data4[i]+data1[n-i]
    ans=max(ans,a,b)
print(ans)

Solution (Python):



import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,c = LI()
xv = [LI() for _ in range(n)]

l1 = [v for x,v in xv]
l2 = l1[:]
r1 = l1[::-1]
r2 = r1[:]

l1 = list(accumulate(l1))
l2 = list(accumulate(l2))
r1 = list(accumulate(r1))
r2 = list(accumulate(r2))

for i,(x,v) in enumerate(xv):
    l1[i] -= x
    l2[i] -= 2*x
    r1[-i-1] -= c - x
    r2[-i-1] -= 2*(c - x)

for i in range(1,n):
    l1[i] = max(l1[i],l1[i-1])
    r1[i] = max(r1[i],r1[i-1])

ans = max(l1[-1],r1[-1])
for i in range(n-1):
    ans = max(ans,l2[i] + r1[-i-2])
    ans = max(ans,r2[i] + l1[-i-2])
print(max(0,ans))

Solution (Python):
n,c=map(int,input().split())
xv = list(list(map(int, input().split())) for i in range(n))
vx=xv[::-1]
sushi1, max1, sushi2, max2 = [0], [0], [0], [0]
import numpy as np

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 vx:
    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 Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools


import queue
from collections import deque




def main():
    num_sushi, length = map(int, input().split())
    data = [list(map(int, input().split())) for i in range(num_sushi)]

    ans = 0
    right1 = [0 for i in range(num_sushi)]
    right1_max = [0 for i in range(num_sushi)]
    for i in range(num_sushi):
        x, v = data[i]
        if i == 0:
            right1[i] = v - x
            right1_max[i] = max(0, right1[i])
        else:
            right1[i] = right1[i - 1] + v - (x - data[i - 1][0])
            right1_max[i] = max(right1_max[i - 1], right1[i])
        ans = max(ans, right1_max[i])

    left1 = [0 for i in range(num_sushi)]
    left1_max = [0 for i in range(num_sushi)]
    for i in range(num_sushi)[::-1]:
        x, v = data[i]
        x = length - x
        if i == num_sushi - 1:
            left1[i] = v - x
            left1_max[i] = max(0, left1[i])
        else:
            left1[i] = left1[i + 1] + v - (data[i + 1][0] - data[i][0])
            left1_max[i] = max(left1_max[i + 1], left1[i])
        ans = max(ans, left1_max[i])

    right2 = [0 for i in range(num_sushi)]
    for i in range(num_sushi - 1):
        x, v = data[i]
        if i == 0:
            right2[i] = v - 2 * x
        else:
            right2[i] = right2[i - 1] + v - 2 * (data[i][0] - data[i - 1][0])
        
        ans = max(ans, right2[i] + left1_max[i + 1])

    left2 = [0 for i in range(num_sushi)]
    for i in range(1, num_sushi)[::-1]:
        x, v = data[i]
        x = length - x
        if i == num_sushi - 1:
            left2[i] = v - 2 * x
        else:
            left2[i] = left2[i + 1] + v - 2 * (data[i + 1][0] - data[i][0])
        ans = max(ans, left2[i] + right1_max[i - 1])

    print(ans)









if __name__ == '__main__':
    main()

Solution (Python):
from itertools import accumulate

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

X = XV[::2] + [C]
A = [0] + list(accumulate(XV[1::2]))

ans = L = R = 0
for b in range(N + 1):
    T = A[N] - A[b]
    d = C - X[b]

    L = max(L, A[b] - X[b - 1])
    R = max(R, A[b] - 2 * X[b - 1])

    ans = max(ans, L + T - 2 * d, R + T - d)

print(ans)

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

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

    ans = 0

    R = [0]
    x0, v0 = 0, 0
    for i in range(N):
        x, v = XV[i]
        v0 += v-(x-x0)
        x0 = x
        R.append(max(v0, R[-1]))
        ans = max(ans, v0)

    L = [0]
    x0, v0 = C, 0
    for i in reversed(range(N)):
        x, v = XV[i]
        v0 += v-(x0-x)
        x0 = x
        L.append(max(v0, L[-1]))
        ans = max(ans, v0)

    x0, v0 = 0, 0
    for r in range(N):
        x, v = XV[r]
        v0 += v-2*(x-x0)
        x0 = x
        ans = max(ans, v0+L[N-1-r])

    x0, v0 = C, 0
    for l in reversed(range(N)):
        x, v = XV[l]
        v0 += v-2*(x0-x)
        x0 = x
        ans = max(ans, v0+R[l])

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, C = MAP()
x = [0] * N
v = [0] * N
for i in range(N):
	x[i], v[i] = MAP()

A = [0] * N
v_tmp = 0
for i in range(N):
	v_tmp += v[i]
	A[i] = v_tmp - x[i]

B = [0] * N
v_tmp = 0
for i in range(N-1, -1, -1):
	v_tmp += v[i]
	B[i] = v_tmp - (C-x[i])

gA = [0] * N
gA[0] = A[0]
for i in range(1, N):
	gA[i] = max(gA[i-1], A[i])

gB = [0] * N
gB[N-1] = B[N-1]
for i in range(N-2, -1, -1):
	gB[i] = max(gB[i+1], B[i])

a = max(A)
b = max(B)
c, d = 0, 0
if N > 1:
	c = max([A[i]-x[i]+gB[i+1] for i in range(N-1)])
	d = max([B[i]-(C-x[i])+gA[i-1] for i in range(N-1, 0, -1)])

print(max(a, b, c, d, 0))

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

l1 = [xv[i][1] for i in range(N)]
l2 = l1[::]
r1 = l1[::-1]
r2 = r1[::]

for i in range(1, N) :
    l1[i] += l1[i-1]
    l2[i] += l2[i-1]
    r1[i] += r1[i-1]
    r2[i] += r2[i-1]
    
for i in range(N) :
    x = xv[i][0]
    l1[i] -= x
    l2[i] -= 2 * x
    r1[N-1-i] -= C - x
    r2[N-1-i] -= 2 * (C - x)

for i in range(1, N) :
    l1[i] = max(l1[i], l1[i-1])
    r1[i] = max(r1[i], r1[i-1])

ret = max(l1[-1], r1[-1])
for i in range(N-1) :
    ret = max(ret, l2[i] + r1[N-2-i])
    ret = max(ret, r2[i] + l1[N-2-i])
    
print(max(ret, 0))

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, c = LI()
clock_pos = []
value = []
for i, j in LIR(n):
    clock_pos += [i]
    value += [j]




arr = [0]
counter_arr = [0]
round_arr = [0]
round_counter_arr = [0]
ret = 0
counter_ret = 0
for i in range(n):
    ret += value[i]
    counter_ret += value[-i - 1]
    arr.append(max(arr[i], ret - clock_pos[i]))
    round_arr.append(ret - clock_pos[i] * 2)
    counter_arr.append(max(counter_arr[i], counter_ret - (c - clock_pos[-i - 1])))
    round_counter_arr.append(counter_ret - (c - clock_pos[-i - 1]) * 2)



ans = max(arr[-1], counter_arr[-1])
for j in range(n):
    ans = max(ans, round_arr[j] + counter_arr[n - j], round_counter_arr[j] + arr[n - j])


print(ans)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, c = LI()
clock_pos = []
value = []
for i, j in LIR(n):
    clock_pos += [i]
    value += [j]




arr = [0]
counter_arr = [0]
round_arr = [0]
round_counter_arr = [0]
ret = 0
counter_ret = 0
for i in range(n):
    ret += value[i]
    a = arr[i - 1]
    arr.append(max(arr[i], ret - clock_pos[i]))
    round_arr.append(ret - clock_pos[i] * 2)
    counter_ret += value[-i - 1]
    counter_arr.append(max(counter_arr[i], counter_ret - (c - clock_pos[-i - 1])))
    round_counter_arr.append(counter_ret - (c - clock_pos[-i - 1]) * 2)



ans = max(arr[-1], counter_arr[-1])
clock_pos = [0] + clock_pos  + [0]
for j in range(n):
    ans = max(ans, round_arr[j] + counter_arr[n - j], round_counter_arr[j] + arr[n - j])



print(ans)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, c = LI()
clock_pos = []
value = []
for i, j in LIR(n):
    clock_pos += [i]
    value += [j]




counter_clock_pos = [0] + [c - i for i in clock_pos][::-1]
clock_pos = [0] + clock_pos
clock_cumsum = list(accumulate([0] + value))
counter_clock_cumsum = [0] + list(accumulate(value[::-1]))

counter_limit = [0] * (n + 1)
last_max_index = 0
ret = 0
for k in range(n + 1):
    remain = counter_clock_cumsum[k] - counter_clock_pos[k]
    if remain > ret:
        ret = remain
        last_max_index = k
    counter_limit[k] = last_max_index


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

    ans = max(ans, clock_cumsum[i] - clock_pos[i] * 2 + counter_clock_cumsum[
        counter_limit[n - i]] - counter_clock_pos[counter_limit[n - i]])


limit = [0] * (n + 1)
last_max_index = 0
ret = 0
for k in range(n + 1):
    remain = clock_cumsum[k] - clock_pos[k]
    if remain > ret:
        ret = remain
        last_max_index = k
    limit[k] = last_max_index


for j in range(n + 1):
    ans = max(ans, counter_clock_cumsum[j] - counter_clock_pos[j] * 2 + clock_cumsum[limit[n - j]] - clock_pos[
        limit[n - j]])



for m in range(n + 1):
    ans = max(ans, clock_cumsum[m] - clock_pos[m])


for p in range(n + 1):
    ans = max(ans, counter_clock_cumsum[p] - counter_clock_pos[p])


print(ans)

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

n, c = map(int, input().split())
sushi = [tuple(map(int, input().split())) for _ in range(n)]

ans = 0

cand1 = [0] * n
v_sum = 0
for i in range(n):
    v_sum += sushi[i][1]
    cand1[i] = v_sum - sushi[i][0]
    if i > 0:
        cand1[i] = max(cand1[i], cand1[i-1])

cand2 = [0] * n
v_sum = 0
for i in reversed(range(n)):
    v_sum += sushi[i][1]
    cand2[i] = v_sum - (c - sushi[i][0])
    if i != n - 1:
        cand2[i] = max(cand2[i], cand2[i+1])

ans = max(ans, max(cand1), max(cand2))

v_sum = 0
for i in reversed(range(1, n)):
    v_sum += sushi[i][1]
    ans = max(ans, v_sum - (c - sushi[i][0]) * 2 + cand1[i-1])

v_sum = 0
for i in range(n-1):
    v_sum += sushi[i][1]
    ans = max(ans, v_sum - sushi[i][0] * 2 + cand2[i+1])

print(ans)

Solution (Python):
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))



N,C = II()
x,v = Line(N)


ans1 = 0
a = []
for i in range(N):
    a.append([x[i],v[i]])
a2 = sorted(a,key=lambda x:x[0])
temp = 0
for i in range(N):
    temp += a2[i][1]
    if temp-a2[i][0]>ans1:
        ans1 = temp-a2[i][0]


ans2 = 0
temp = 0
for i in range(N)[::-1]:
    temp += a2[i][1]
    if temp-(C-a2[i][0])>ans2:
        ans2 = temp-(C-a2[i][0])

ans = max(ans1,ans2)


b = [] 
temp = 0
for i in range(N)[::-1]:
    temp += a[i][1]
    b.append([N-i,temp-2*(C-a[i][0])])
b.sort(key=lambda x:-x[1])
now = 0
a_temp = 0
for i in range(N):
    a_temp += a[i][1]
    while now<=N-1:
        if b[now][0]+i+1>N:
            now += 1
        else:
            temp = b[now][1]+a_temp-a[i][0]
            if temp>ans:
                ans = temp
            break


b = [] 
temp = 0
for i in range(N):
    temp += a[i][1]
    b.append([i+1,temp-2*a[i][0]])
b.sort(key=lambda x:-x[1])
now = 0
a_temp = 0
for i in range(N)[::-1]:
    a_temp += a[i][1]
    while now<=N-1:
        if b[now][0]+N-i>N:
            now += 1
        else:
            temp = b[now][1]+a_temp-(C-a[i][0])
            if temp>ans:
                ans = temp
            break

print(ans)

Solution (Python):
from itertools import accumulate as acc
N, C = map(int, input().split())
ds, vs = [], []
for i in range(N):
  d, v = map(int, input().split())
  ds.append(d)
  vs.append(v)
rvcs = list(acc(vs))
lvcs = list(acc(vs[:: -1]))
rds = ds
lds = [C - d for d in ds[:: -1]]
re = [v - d for d, v in zip(rds, rvcs)]
le = [v - d for d, v in zip(lds, lvcs)]
remax = [0]
lemax = [0]
for i in range(N):
  remax.append(max(remax[-1], re[i]))
  lemax.append(max(lemax[-1], le[i]))
res = 0



for i in range(N):
  res = max(res, re[i], le[i], re[i] + lemax[N - i - 1] - rds[i], le[i] + remax[N - i - 1] - lds[i])
print(res)

Solution (Python):
def main():

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

    clock = [0]
    clock_r = [0]
    v = 0
    for i in range(N):
        v += A[i][1]
        clock.append(v-A[i][0])
        clock_r.append(v-2*A[i][0])
    prefix_clock = [0]
    prefix_clock_r = [0]
    for i in range(1, N+1):
        prefix_clock.append(max(prefix_clock[-1], clock[i]))
        prefix_clock_r.append(max(prefix_clock_r[-1], clock_r[i]))

    cclock = [0]
    cclock_r = [0]
    v = 0
    for i in range(N):
        v += A[N-1-i][1]
        cclock.append(v-(C-A[N-1-i][0]))
        cclock_r.append(v-2*(C-A[N-1-i][0]))
    prefix_cclock = [0]
    prefix_cclock_r = [0]
    for i in range(1, N+1):
        prefix_cclock.append(max(prefix_cclock[-1], cclock[i]))
        prefix_cclock_r.append(max(prefix_cclock_r[-1], cclock_r[i]))

    
    
    

    max_v = float('-inf')
    for i in range(N+1):
        v1 = prefix_clock_r[i]
        v2 = prefix_cclock[N-i]
        max_v = max(max_v, v1+v2)
        v3 = prefix_clock[i]
        v4 = prefix_cclock_r[N-i]
        max_v = max(max_v, v3+v4)
    return max_v


if __name__ == '__main__':
    print(main())

Solution (Python):
n, c = map(int, input().split())
XR = [list(map(int,input().split())) for i in range(n)]
XL = [[c-XR[i][0], XR[i][1]] for i in range(n)]
XL.sort()

CR = []
cal = 0
for i in range(n):
    dis = XR[i][0]
    cal += XR[i][1]
    CR.append([cal-dis, dis])


CSR = [CR[0][0]]
for i in range(n-1):
    CSR.append(max(CSR[i], CR[i+1][0]))

CL = []
cal = 0
for i in range(n):
    dis = XL[i][0]
    cal += XL[i][1]
    CL.append([cal-dis, dis])


CSL = [CL[0][0]]
for i in range(n-1):
    CSL.append(max(CSL[i], CL[i+1][0]))







ans = max(max(CSR), max(CSL))
for i in range(n-1):
    
    ans = max(ans, CL[i][0]-CL[i][1]+CSR[n-2-i])
    ans = max(ans, CR[i][0]-CR[i][1]+CSL[n-2-i])

print(max(ans, 0))