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):
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))

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


rc=[v[0]-2*x[0]]
for j in range(1,N):
    rc.append(rc[-1]+v[j]-2*(x[j]-x[j-1]))


mrc=[rc[0]]
for j in range(1,N):
    mrc.append(max(mrc[-1],rc[j]))


ca=[v[N-1]-(C-x[N-1])]
for i in range(1,N):
    ca.append(ca[-1]+v[N-1-i]-(x[N-i]-x[N-1-i]))


mca=[ca[0]]
for i in range(1,N):
    mca.append(max(mca[-1],ca[i]))




ra=[v[N-1]-2*(C-x[N-1])]
for j in range(1,N):
    ra.append(ra[-1]+v[N-1-j]-2*(x[N-j]-x[N-1-j]))

mra=[ra[0]]
for j in range(1,N):
    mra.append(max(mra[-1],ra[j]))



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

mcc=[cc[0]]
for i in range(1,N):
    mcc.append(max(mcc[-1],cc[i]))


ans=0
if N==1:
    ans=max(ans,v[0]-x[0],v[0]-(C-x[0]))
else:
    
    for i in range(N-1):
        ans=max(ans,mrc[i]+mca[N-2-i])
    
    

    
    for i in range(N):
        ans=max(ans,mcc[i])

    
    for i in range(N-1):
        ans=max(ans,mra[i],mra[i]+mcc[N-2-i])
    
    
    for i in range(N):
        ans=max(ans,mca[i])

print(ans)

Solution (Python):
from itertools import accumulate as f

def main():
	n, c, *L = map(int, open(0).read().split())
	acc = [a - x for x, a in zip(L[::2], f(L[1::2]))]
	acc_max = list(f(acc, max))[::-1]
	R = L[::-1]
	rev = [a - (c - x) for x, a in zip(R[1::2], f(R[::2]))]
	rev_max = list(f(rev, max))[::-1]
	p = max([a - b + d for a, b, d in zip(acc, L[::2], rev_max[1:])]+[0])
	q = max([a - (c - b) + d for a, b, d in zip(rev, R[1::2], acc_max[1:])]+[0])
	r = max(0, acc_max[0], rev_max[0])
	print(max(p, q, r))

if __name__ == "__main__":
	main()

Solution (Python):
from itertools import*
n,c,*L=map(int,open(0).read().split())
acc=[a-x for x,a in zip(L[::2],accumulate(L[1::2]))]
acc_max=list(accumulate([0]+acc,max))
R=L[::-1]
rev=[a-(c-x) for x,a in zip(R[1::2],accumulate(R[::2]))]
rev_max=list(accumulate([0]+rev,max))
p=max(rev_max[n-i-1]+a-b for i,(a,b) in enumerate(zip(acc,L[::2])))
q=max(acc_max[n-i-1]+a-(c-b) for i,(a,b) in enumerate(zip(rev,R[1::2])))
r=max(0,acc_max[-1],rev_max[-1])
print(max(p,q,r))

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

R = [[0 for _ in range(4)] for _ in range(N)]
L = [[0 for _ in range(4)] for _ in range(N)]

for i in range(N):
  R[i][3] = 0
  L[i][3] = 0

for i in range(N):
  R[i][0] = XV[i][0]
  R[i][1] = XV[i][1]
  L[i][0] = C - XV[i][0]
  L[i][1] = XV[i][1]
L.sort()

for i in range(N):
  R[i][2] = R[i - 1][2] + R[i][1]
  L[i][2] = L[i - 1][2] + L[i][1]
for i in range(N):
  R[i][2] -= R[i][0]
  L[i][2] -= L[i][0] 
  R[i][3] = max(R[i - 1][3], R[i][2])
  L[i][3] = max(L[i - 1][3], L[i][2])



answer = []
for i in range(N):
  if i != N - 1:
    answer.append(R[i][2] + max(L[N - 2 - i][3] - R[i][0], 0))
  else:
    answer.append(R[i][2])

L, R = R, L
for i in range(N):
  if i != N - 1:
    answer.append(R[i][2] + max(L[N - 2 - i][3] - R[i][0], 0))
  else:
    answer.append(R[i][2])

answer = max(answer)
print(answer if answer > 0 else 0)

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

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


accL = [0] * (N+1)
cur = 0
for i in range(1, N+1):
    x, v = L[i]
    dist = x - L[i-1][0]
    cur +=  v - dist
    accL[i] = max(accL[i-1], cur)
accR = [0] * (N+1)
cur = 0
for i in range(1, N+1):
    x, v = R[i]
    dist = x - R[i-1][0]
    cur +=  v - dist
    accR[i] = max(accR[i-1], cur)

ans = max(max(accL), max(accR))

for i in range(N+1):
    
    ans = max(ans, accL[i] - L[i][0] + accR[N-i])
    
    ans = max(ans, accR[i] - R[i][0] + accL[N-i])
print(ans)

Solution (Python):


import sys
import numpy as np

N, C = map(int, sys.stdin.buffer.readline().split())
x, v = [], []
for _ in range(N):
    tmp, tmp2 = map(int, sys.stdin.buffer.readline().split())
    x.append(tmp)
    v.append(tmp2)

x = np.array(x, np.int64)
v = np.array(v, np.int64)
v_cum = v.cumsum()
tx = np.flipud(x)
tv_cum = np.flipud(v).cumsum()
left_cum = v_cum - x

right_cum = tv_cum - np.flipud(C - x)
right_cum_max = np.maximum.accumulate(right_cum)

right_cum_return = right_cum - np.flipud(C - x)
right_cum_return_max = np.maximum.accumulate(right_cum_return)

ans = max(0, np.max(left_cum), np.max(right_cum))

for first_abandon_idx in range(1, N):
    ans = max(ans, left_cum[first_abandon_idx-1] - x[first_abandon_idx-1] + right_cum_max[N-1 - first_abandon_idx])
    ans = max(ans, left_cum[first_abandon_idx-1] + right_cum_return_max[N-1 - first_abandon_idx])

print(ans)

Solution (Python):
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time

def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase


input=lambda: sys.stdin.readline().rstrip()

show_flg=False


n,c=LI()
s=[]

for i in range(n):
    x,v=LI()
    s.append((x,v))

show(c,s)
def solve(s):
    show('s',s)
    rt=-inf
    n=len(s)
    av=[0]
    for i in range(n):
        av.append(av[-1]+s[i][1])
    
    rav=[0]
    for i in range(n):
        rav.append(rav[-1]+s[-i-1][1])
    
    f=[-inf]*(n+1)
    for i in range(n):
        f[i+1]=max(av[i+1]-s[i][0],f[i])
    f.append(-inf)
    
    for i in range(1,n+1):
        rt=max(rt,rav[i]-(c-s[-i][0]),rav[i]-(c-s[-i][0])*2+f[n-i])

    return rt

ans=solve(s)
ans=max(ans,solve([(c-x,v) for x,v in s[::-1]]),0)
print(ans)

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


n, c = map(int, input().split())
sushi = [list(map(int, input().split())) for _ in range(n)]
half = c//2

DP_left = {}
DP_right = {}
ans = []

energy = 0
maxim = 0
prev = 0
for pos, cal in sushi:
    lost = pos - prev
    energy += cal - lost
    maxim = max(maxim, energy)
    DP_left[pos] = maxim
    prev = pos
ans.append(maxim)


energy = 0
maxim = 0
prev = c
for pos, cal in sushi[::-1]:
    lost = prev - pos
    energy += cal - lost
    maxim = max(maxim, energy)
    DP_right[pos] = maxim
    prev = pos
ans.append(maxim)


energy = 0
maxim = 0
prev = 0
for idx, (pos, cal) in enumerate(sushi):
    if idx == n-1:
        break
    if pos > half:
        break
    lost = pos - prev
    energy += cal - lost
    next_pos, _ = sushi[idx+1]
    back_cost = pos
    result = energy - back_cost + DP_right[next_pos]
    maxim = max(maxim, result)
    prev = pos
ans.append(maxim)


energy = 0
maxim = 0
prev = c
for idx, (pos, cal) in enumerate(sushi[::-1], 1):
    if idx == n:
        break
    if pos < half:
        break
    lost = prev - pos
    energy += cal - lost
    back_cost = c - pos
    next_pos, _ = sushi[-idx-1]
    result = energy - back_cost + DP_left[next_pos]
    maxim = max(maxim, result)
    prev = pos
ans.append(maxim)

print(max(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
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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 pos, v in LIR(n):
    clock_pos += [pos]
    value += [v]


rounding_max = [0]
counter_rounding_max = [0]
return_max = [0]
counter_return_max = [0]
ret = 0
counter_ret = 0
for i in range(n):
    ret += value[i]
    counter_ret += value[-i - 1]
    rounding_max += [max(rounding_max[-1], ret - clock_pos[i])]
    counter_rounding_max += [max(counter_rounding_max[-1], counter_ret - (c - clock_pos[-i - 1]))]
    return_max += [max(return_max[-1], ret - clock_pos[i] * 2)]
    counter_return_max += [max(counter_return_max[-1], counter_ret - (c - clock_pos[-i - 1]) * 2)]



ans = max(rounding_max[-1], counter_rounding_max[-1])
for j in range(1, n + 1):
    ans = max(ans, return_max[j] + counter_rounding_max[n - j], counter_return_max[j] + rounding_max[n - j])


print(ans)

Solution (Python):
N, C = map(int, input().split())
INF = 10**20
rightSushi = [tuple(map(int, input().split())) for _ in range(N)]
leftSushi = [(C - x, v) for x, v in rightSushi[:: -1]]

def calc(sushi):
    ret = [-INF] * (N + 1)
    ret[0] = 0
    vSum = 0
    for i, (x, v) in enumerate(sushi, start=1):
        vSum += v
        ret[i] = max(vSum - x, ret[i - 1])
    return ret

leftV = calc(leftSushi)
rightV = calc(rightSushi)

def sol(sushi, maxV):
    ret = 0
    vSum = 0
    for i, (x, v) in enumerate(sushi, start=1):
        vSum += v
        ret = max(
            ret,
            vSum - x,
            vSum - x * 2 + maxV[N - i]
        )
    return ret

ans = max(sol(rightSushi, leftV), sol(leftSushi, rightV))

print(ans)

Solution (Python):
N, C = map(int, input().split())
INF = 10**20
rightSushi = [tuple(map(int, input().split())) for _ in range(N)]
leftSushi = [(C - x, v) for x, v in rightSushi[:: -1]]

def calc(sushi):
    ret = [-INF] * (N + 1)
    ret[0] = 0
    vSum = 0
    for i, (x, v) in enumerate(sushi, start=1):
        vSum += v
        ret[i] = max(vSum - x, ret[i - 1])
    return ret

leftV = calc(leftSushi)
rightV = calc(rightSushi)

ans = 0
vSum = 0
for right, (x, v) in enumerate(rightSushi, start=1):
    vSum += v
    ans = max(
        ans,
        vSum - x,
        vSum - x * 2 + leftV[N - right]
    )

vSum = 0
for left, (x, v) in enumerate(leftSushi, start=1):
    vSum += v
    ans = max(
        ans,
        vSum - x,
        vSum - x * 2 + rightV[N - left]
    )

print(ans)

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

cumsum = [(0, 0)]
cumsum_max = [(0, 0)]
prev = 0
for x, v in sushi[1:]:
    cumsum.append((x, cumsum[-1][1] + prev + v - x))
    cumsum_max.append(cumsum_max[-1] if cumsum_max[-1][1] > cumsum[-1][1] else cumsum[-1])
    prev = x
cumsum_rev = [(0, 0)]
cumsum_rev_max = [(0, 0)]
prev = 0
for x, v in reversed(sushi[1:]):
    cumsum_rev.append((C - x, cumsum_rev[-1][1] + prev + v - (C - x)))
    cumsum_rev_max.append(cumsum_rev_max[-1] if cumsum_rev_max[-1][1] > cumsum_rev[-1][1] else cumsum_rev[-1])
    prev = C - x
ans = 0
for i in range(N+1):
    temp1 = cumsum_max[N-i][1] + cumsum_rev[i][1] - cumsum_rev[i][0]
    temp2 = cumsum_rev_max[N-i][1] + cumsum[i][1] - cumsum[i][0]
    ans = max(ans, temp1, temp2)
print(ans)

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

X = [0]
V = [0]
sV = [0]
Amax1 = [0]
Amax2 = [0]
for _ in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)
    sV.append(sV[-1]+v)
    Amax1.append(max(Amax1[-1], sV[-1]-x))
    Amax2.append(max(Amax2[-1], sV[-1]-2*x))
X.append(C)

ans = 0
for b in range(1, N+2):
    
    a1 = Amax2[b-1]+sV[-1]-sV[b-1]-(C-X[b])

    
    a2 = Amax1[b-1]+sV[-1]-sV[b-1]-2*(C-X[b])

    ans = max(ans, a1, a2)

print(ans)

Solution (Python):
mininf = 0

def cumsum(inlist):
    s = 0
    outlist = []
    for i in inlist:
        s += i
        outlist.append(s)
    return outlist

def maxtohere(inlist):
    s = mininf
    outlist = []
    for i in inlist:
        s = max(s, i)
        outlist.append(s)
    return outlist

n, length = [int(v) for v in input().split()]
sushi = [[int(v) for v in input().split()] for i in range(n)]

diff_distance_from_left = [sushi[i][0] - sushi[i-1][0] if i > 0 else sushi[0][0] for i in range(n)]
diff_distance_from_right = [sushi[i+1][0] - sushi[i][0] if i < n-1 else length - sushi[i][0] for i in range(n-1,-1,-1)]
sushi_oneway_from_left = [sushi[i][1]-diff_distance_from_left[i] for i in range(n)]
sushi_oneway_from_right = [sushi[-i-1][1] - diff_distance_from_right[i] for i in range(n)]
sushi_roundtrip_from_left = [sushi[i][1]-diff_distance_from_left[i]*2 for i in range(n)]
sushi_roundtrip_from_right = [sushi[-i-1][1] - diff_distance_from_right[i]*2 for i in range(n)]

sum_of_sushi_oneway_from_left = cumsum(sushi_oneway_from_left)
sum_of_sushi_roundtrip_from_left = cumsum(sushi_roundtrip_from_left)
sum_of_sushi_oneway_from_right = cumsum(sushi_oneway_from_right)
sum_of_sushi_roundtrip_from_right = cumsum(sushi_roundtrip_from_right)

sum_of_sushi_oneway_from_left = maxtohere(sum_of_sushi_oneway_from_left)
sum_of_sushi_roundtrip_from_left = maxtohere(sum_of_sushi_roundtrip_from_left)
sum_of_sushi_oneway_from_right = maxtohere(sum_of_sushi_oneway_from_right)
sum_of_sushi_roundtrip_from_right = maxtohere(sum_of_sushi_roundtrip_from_right)

sum_of_sushi_from_left = sum_of_sushi_oneway_from_left
sum_of_sushi_from_right = sum_of_sushi_oneway_from_right
for i in range(n-1):
    sum_of_sushi_from_left[i] += sum_of_sushi_roundtrip_from_right[-2-i]
for i in range(n-1):
    sum_of_sushi_from_right[i] += sum_of_sushi_roundtrip_from_left[-2-i]

print(max(sum_of_sushi_from_left+sum_of_sushi_from_right))

Solution (Python):
n,c=map(int,input().split())
X,V=[0],[0]
X2,V2=[],[]
for _ in range(n):
    x,v=map(int,input().split())
    X.append(x)
    V.append(v)
    X2.append(c-x)
    V2.append(v)
X2.append(0)
V2.append(0)
X2.reverse()
V2.reverse()
r=[0]
l=[0]
for i in range(n):
    V[i+1]+=V[i]
    V2[i+1]+=V2[i]
rr=[0]
ll=[0]
for i in range(1,n+1):
    r.append(max(r[-1],V[i]-X[i]))
    rr.append(max(rr[-1],V[i]-2*X[i]))
for i in range(1,n+1):
    l.append(max(l[-1],V2[i]-X2[i]))
    ll.append(max(ll[-1],V2[i]-2*X2[i]))
ans=0
for i in range(n+1):
    ans=max(ans,r[i]+ll[n-i],l[i]+rr[n-i])

print(ans)

Solution (Python):

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





xv_list = [(0,0)]
total_cal_list_cw = [0] 
max_total_cal_list_cw = [0] 
max_total_cal_cw = 0

for i in range(1,N+1): 
    x,v = map(int, input().split())
    xv_list.append((x,v))
    total_cal_cw = total_cal_list_cw[i-1] + v - x + xv_list[i-1][0]
    total_cal_list_cw.append(total_cal_cw)
    
    if max_total_cal_cw < total_cal_cw:
        max_total_cal_cw = total_cal_cw
        
    max_total_cal_list_cw.append(max_total_cal_cw)


rev_xv_list = [(0,0)] + [(C - xv[0],xv[1]) for xv in xv_list[:-(N+1):-1]] 
total_cal_list_acw = [0] 
max_total_cal_list_acw = [0]
max_total_cal_acw = 0

for i in range(1,N+1): 
    x,v = rev_xv_list[i][0],rev_xv_list[i][1]
    total_cal_acw = total_cal_list_acw[i-1] + v - x + rev_xv_list[i-1][0]
    total_cal_list_acw.append(total_cal_acw)
    
    if max_total_cal_acw < total_cal_acw:
        max_total_cal_acw = total_cal_acw
    
    max_total_cal_list_acw.append(max_total_cal_acw)    

    

ans = 0

for i in range(1,N+1): 
    
    
    if ans < total_cal_list_cw[i]:
        ans = total_cal_list_cw[i]
    
    total_cal = total_cal_list_cw[i] - xv_list[i][0] 
    if total_cal > 0:
        total_cal += max_total_cal_list_acw[N-i]
        if ans < total_cal:
            ans = total_cal
    
    
    
    if ans < total_cal_list_acw[i]:
        ans = total_cal_list_acw[i]
    
    total_cal = total_cal_list_acw[i] - rev_xv_list[i][0] 
    if total_cal > 0:
        total_cal += max_total_cal_list_cw[N-i]
        if ans < total_cal:
            ans = total_cal
        
print(ans)

Solution (Python):
import sys
from itertools import accumulate
import bisect
n, c = [int(i) for i in sys.stdin.readline().split()]
x_ls = []
inv_x_ls = []
v_ls = []
for i in range(n):
    x, v = [int(i) for i in sys.stdin.readline().split()]
    x_ls.append(x)
    inv_x_ls.append(c - x)
    v_ls.append(v)
inv_v_ls = v_ls[::-1]
inv_x_ls = inv_x_ls[::-1]
v_ls = [0] + [v - x for v, x in zip(accumulate(v_ls), x_ls)]
inv_v_ls = [0] + [v - x for v, x in zip(accumulate(inv_v_ls), inv_x_ls)]
x_ls = [0] + x_ls
inv_x_ls = [0] + inv_x_ls
best_v = 0
best_inv_v = 0
for i in range(n + 1):
    best_v = max(best_v, v_ls[i])
    best_inv_v = max(best_inv_v, inv_v_ls[i])
    v_ls[i] = best_v
    inv_v_ls[i] = best_inv_v

best = 0
for tokei in range(n+1):
    tokei_dis = x_ls[tokei]
    hantokei = max(0, inv_v_ls[n - tokei] - tokei_dis)
    res = v_ls[tokei] + hantokei
    best = max(best, res)
for hantokei in range(n+1):
    hantokei_dis = inv_x_ls[hantokei]
    tokei = max(0, v_ls[n - hantokei] - hantokei_dis)
    res = inv_v_ls[hantokei] + tokei
    best = max(best, res)
print(best)

Solution (Python):
N, C = map(int,input().split())
sushi = list(list(map(int,input().split()))for i in range(N))
r1,l1,r2,l2 = [0]*(N+1),[0]*(N+1),[0]*(N+1),[0]*(N+1)

eat = 0
for i in range(N):
    a,b = sushi[i]
    eat += b
    r1[i+1] = max(r1[i],eat-a)
    r2[i+1] = max(r2[i],eat-a*2)
eat = 0
for i in range(N-1,-1,-1):
    a,b = sushi[i]
    eat += b
    l1[i] = max(l1[i+1],eat-(C-a))
    l2[i] = max(l2[i+1],eat-(C-a)*2)

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

print(ans)

Solution (Python):

import sys
from itertools import accumulate

def rightTrip(x,v,N,C)->int:
    accum_v = list(accumulate(v))
    
    left_v = v[::-1]
    left_accum_v = list(accumulate(left_v))

    
    rightRoundTrip = [accum_v[i]-2*x[i] for i in range(N)]
    """
    右行って左
    """
    dp_left = [0]*(N)
    dp_left[0] = left_v[0] - (C-x[N-1])
    
    for i in range(1,N):
        dp_left[i] = max(left_accum_v[i]-(C-x[N-i-1]),dp_left[i-1])
    
    answer = 0
    

    for i in range(0,N-1):
        r = rightRoundTrip[i]
        l = dp_left[N-2-i]
        answer = max(r+l,answer)
    
    """
    右行って退店
    """
    rightTrip = [accum_v[i]-x[i] for i in range(N)]
    answer = max(answer,max(rightTrip))
    return answer

def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    
    
    
    
    left_v = v[::-1]
    left_x = [C-x[i] for i in range(N-1,-1,-1)]
    print(max(rightTrip(x,v,N,C),rightTrip(left_x,left_v,N,C)))
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    C = int(next(tokens))  
    x = [int()] * (N)  
    v = [int()] * (N)  
    for i in range(N):
        x[i] = int(next(tokens))
        v[i] = int(next(tokens))
    solve(N, C, x, v)

if __name__ == '__main__':
    main()

Solution (Python):
N, C = map(int, input().split())
V = [0]
X = [0]
Y = []
for i in range(N):
  x, v = map(int, input().split())
  X += [x]
  Y += [C-x]
  V += [v]
Y += [0]
f = [0]
g = [0]
for i in range(1,N+1):
  f += [f[-1]+X[i-1]+V[i]-X[i]]
  g += [g[-1]+Y[N-i+1]+V[N-i+1]-Y[N-i]]
g = g[::-1]

m = -1
ans1 = 0
for i in range(N+1):
  if m<f[i]:
    m = f[i]
  ans1 = max(ans1, m+g[i]-Y[i])

m = -1
ans2 = 0
for i in range(N, -1, -1):
  if m<g[i]:
    m = g[i]
  ans2 = max(ans2, m+f[i]-X[i])

print(max(ans1, ans2))

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):
def main():
    import sys
    input = sys.stdin.readline
    N, C = map(int, input().split())

    left = []
    right = []
    left_append = left.append
    right_append = right.append
    for _ in range(N):
        x, v = map(int, input().split())
        left_append([x, v])
        right_append([C - x, v])

    tmp1 = max(0, left[0][1] - left[0][0])
    left_value = [0, tmp1]
    tmp2 = max(0, left[0][1] - 2 * left[0][0])
    left_value_back = [0, tmp2]
    left_value_append = left_value.append
    left_value_back_append = left_value_back.append
    for i in range(1, N):
        left[i][1] += left[i - 1][1]
        tmp1 = max(tmp1 ,left[i][1] - left[i][0])
        left_value_append(tmp1)
        tmp2 = max(tmp2 ,left[i][1] - 2 * left[i][0])
        left_value_back_append(tmp2)

    tmp1 = max(0, right[N - 1][1] - right[N - 1][0])
    right_value = [0, tmp1]
    tmp2 = max(0, right[N- 1][1] - 2 * right[N - 1][0])
    right_value_bakc = [0, tmp2]
    right_value_append = right_value.append
    right_value_bakc_append = right_value_bakc.append
    for i in range(N- 2, -1, -1):
        right[i][1] += right[i + 1][1]
        tmp1 = max(tmp1, right[i][1] - right[i][0])
        right_value_append(tmp1)
        tmp2 = max(tmp2, right[i][1] - 2 * right[i][0])
        right_value_bakc_append(tmp2)

    
    
    
    
    
    
    

    ans = 0
    for i in range(N + 1):
        tmp = max(left_value[i], right_value[N - i])
        tmp = max(tmp, left_value_back[i] + right_value[N - i], left_value[i] + right_value_bakc[N - i])
        ans = max(ans, tmp)

    print (ans)

if __name__ == '__main__':
    main()

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

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

tmp1 = max(0, left[0][1] - left[0][0])
left_value = [0, tmp1]
tmp2 = max(0, left[0][1] - 2 * left[0][0])
left_value_back = [0, tmp2]
for i in range(1, N):
    left[i][1] += left[i - 1][1]
    tmp1 = max(tmp1 ,left[i][1] - left[i][0])
    left_value.append(tmp1)
    tmp2 = max(tmp2 ,left[i][1] - 2 * left[i][0])
    left_value_back.append(tmp2)

tmp1 = max(0, right[N - 1][1] - right[N - 1][0])
right_value = [0, tmp1]
tmp2 = max(0, right[N- 1][1] - 2 * right[N - 1][0])
right_value_bakc = [0, tmp2]
for i in range(N- 2, -1, -1):
    right[i][1] += right[i + 1][1]
    tmp1 = max(tmp1, right[i][1] - right[i][0])
    right_value.append(tmp1)
    tmp2 = max(tmp2, right[i][1] - 2 * right[i][0])
    right_value_bakc.append(tmp2)









ans = 0
for i in range(N + 1):
    tmp = max(left_value[i], right_value[N - i])
    tmp = max(tmp, left_value_back[i] + right_value[N - i], left_value[i] + right_value_bakc[N - i])
    ans = max(ans, tmp)

print (ans)

Solution (Python):
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 = [tuple(map(int,input().split())) 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]+xv[i][1]-(xv[i][0]-dis)
        r2[i+1] = r2[i]+xv[i][1]-2*(xv[i][0]-dis)
        dis = xv[i][0]
    dis = C
    for i in reversed(range(N)):
        l1[N-i]=l1[N-i-1]+xv[i][1]-(dis-xv[i][0])
        l2[N-i]=l2[N-i-1]+xv[i][1]-2*(dis-xv[i][0])
        dis = xv[i][0]
    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()