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

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

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

get_l = []
sum_v = 0
for x, v in xvl:
    sum_v += v
    get_l.append(sum_v - x)

import itertools
get_l_ac = list(itertools.accumulate(get_l, max))
get_r = []
sum_v = 0
for x, v in xvl[::-1]:
    sum_v += v
    get_r.append(sum_v - (c - x))


ans = 0
x = 0
for i in range(n):
    tmp = 0
    if i > 0:
        x = c - xvl[-i][0]
        tmp += get_r[i-1]
    ans = max(tmp, tmp - x + get_l_ac[n - i - 1], ans)

get_r_ac = list(itertools.accumulate(get_r, max))
x = 0
for i in range(n):
    tmp = 0
    if i > 0:
        x = xvl[i-1][0]
        tmp += get_l[i-1]
    ans = max(tmp, tmp - x + get_r_ac[n - i - 1], ans)

print(ans)

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

Y = [[C - i, v] for i, v in X[::-1]]


x_cs = [[0, 0] for _ in range(N + 1)]
y_cs = [[0, 0] for _ in range(N + 1)]
for i in range(N):
    x_cs[i + 1][0] = X[i][0]
    x_cs[i + 1][1] = x_cs[i][1] + X[i][1]

    y_cs[i + 1][0] = Y[i][0]
    y_cs[i + 1][1] = y_cs[i][1] + Y[i][1]

fx = [v - x for x, v in x_cs]
fy = [v - x for x, v in y_cs]

gx = [0] * (N + 1)
gy = [0] * (N + 1)
for i in range(N):
    gx[i + 1] = max(gx[i], fx[i + 1])
    gy[i + 1] = max(gy[i], fy[i + 1])

X = [[0, 0]] + X
Y = [[0, 0]] + Y
ans = max(gx + gy)
for i in range(N + 1):
    ans = max(ans, gx[i] + gy[N - i] - X[i][0],
              gx[N - i] + gy[i] - Y[i][0])

print(ans)

Solution (Python):
from itertools import accumulate
N, C = map(int, input().split())
XV = [tuple(map(int, input().split())) for _ in range(N)]


eat = 0
walk = 0
now = 0
clockwise = [(0, 0)]
for x, v in XV:
    eat += v
    walk += x-now
    clockwise.append((eat, walk))
    now = x


eat = 0
walk = 0
now = C
counter_clockwise = [(0, 0)]
for x, v in XV[::-1]:
    eat += v
    walk += now - x
    counter_clockwise.append((eat, walk))
    now = x


best_left_go = [e - w for e, w in counter_clockwise]
best_left_go = list(accumulate(best_left_go, func=max))
best_left_back = [e - 2 * w for e, w in counter_clockwise]
best_left_back = list(accumulate(best_left_back, func=max))
best_right_go = [e - w for e, w in clockwise]
best_right_go = list(accumulate(best_right_go, func=max))
best_right_back = [e - 2 * w for e, w in clockwise]
best_right_back = list(accumulate(best_right_back, func=max))


ans = 0
for i, rb in enumerate(best_right_back):
    calorie = rb + best_left_go[N - i]
    ans = max(ans, calorie)

for i, lb in enumerate(best_left_back):
    calorie = lb + best_right_go[N - i]
    ans = max(ans, calorie)

print(ans)

Solution (Python):
n, c = map(int, input().split())
XV = [tuple(map(int, input().split())) for i in range(n)]
X = [x for x, v in XV]
V = [v for x, v in XV]
S = [0]
for i in range(n):
    S.append(S[-1]+V[i])

A = [0]
for i in range(1, n+1):
    A.append(max(A[-1], S[i]-2*X[i-1]))
B = []
for i in range(n):
    B.append(S[n]-S[i]-(c-X[i]))
B.append(0)
ans0 = max([A[i]+B[i] for i in range(n+1)])

A = [0]
for i in range(1, n+1):
    A.append(max(A[-1], S[i]-X[i-1]))
B = []
for i in range(n):
    B.append(S[n]-S[i]-2*(c-X[i]))
B.append(0)
ans1 = max([A[i]+B[i] for i in range(n+1)])
print(max(ans0, ans1))

Solution (Python):
def main():
    from collections import namedtuple
    import sys
    input = sys.stdin.readline

    Sushi = namedtuple('Sushi', 'x cal')

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

    a = []
    for _ in range(n):
        x, v = map(int, input().split())
        a.append(Sushi(x=x, cal=v))
    

    clock = [0] * (n + 1)  
    clock_to_0 = [0] * (n + 1)  
    ma = 0  
    ma0 = 0  
    curr = 0  
    for i, s in enumerate(a, start=1):
        curr += s.cal
        ma = max(ma, curr - s.x)
        ma0 = max(ma0, curr - s.x * 2)
        clock[i] = ma
        clock_to_0[i] = ma0

    anti = [0] * (n + 1)  
    anti_to_0 = [0] * (n + 1)  
    ma = 0  
    ma0 = 0  
    curr = 0  
    for i, s in zip(range(n, -1, -1), reversed(a)):
        curr += s.cal
        ma = max(ma, curr - (c - s.x))
        ma0 = max(ma0, curr - (c - s.x) * 2)
        anti[i] = ma
        anti_to_0[i] = ma0

    ans = 0
    for exit_pos in range(1, n + 1):
        ans = max(
            ans,
            clock_to_0[exit_pos - 1] + anti[exit_pos],
            anti_to_0[(exit_pos + 1) % (n + 1)] + clock[exit_pos]
        )

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    from collections import namedtuple
    import sys
    input = sys.stdin.readline

    Sushi = namedtuple('Sushi', 'x cal')

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

    a = []
    for _ in range(n):
        x, v = map(int, input().split())
        a.append(Sushi(x=x, cal=v))
    

    clock = [0] * (n + 1)  
    clock_to_0 = [0] * (n + 1)  
    ma = 0  
    curr = 0  
    for i, s in enumerate(a, start=1):
        curr += s.cal
        ma = max(ma, curr - s.x)
        clock[i] = ma
        clock_to_0[i] = curr - s.x * 2

    anti = [0] * (n + 1)  
    anti_to_0 = [0] * (n + 1)  
    ma = 0  
    curr = 0  
    for i, s in zip(range(n, -1, -1), reversed(a)):
        curr += s.cal
        ma = max(ma, curr - (c - s.x))
        anti[i] = ma
        anti_to_0[i] = curr - (c - s.x) * 2

    ans = 0
    for exit_pos in range(1, n + 1):
        ans = max(
            ans,
            clock_to_0[exit_pos - 1] + anti[exit_pos],
            anti_to_0[(exit_pos + 1) % (n + 1)] + clock[exit_pos]
        )

    print(ans)


if __name__ == '__main__':
    main()

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

xv = [tuple(map(int, input().split())) for i in range(N)]
xv2 = [(C - x, v)for x, v in xv[::-1]]


L = [0]*N
ans = 0
for i, X in enumerate(xv):
    x, v = X
    L[i] = L[i-1] + v
R = [0]*N
for i in range(N):
    L[i] -= xv[i][0]
for i, X in enumerate(xv2):
    x, v = X
    R[i] = R[i-1] + v
for i in range(N):
    R[i] -= xv2[i][0]

LL = [0]*(N+1)
RR = [0]*(N+1)
for i in range(N):
    LL[i+1] = max(LL[i], L[i])
    RR[i+1] = max(RR[i], R[i])

ans = 0
ans = max(ans, LL[-1])
ans = max(ans, RR[-1])
for i in range(N):
    ans = max(ans, LL[N - 1 - i] + R[i] - xv2[i][0])
    ans = max(ans, RR[N - 1 - i] + L[i] - xv[i][0])
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) 
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    


MOD = 10**9 + 7
INF = 2**31  

from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  


N, C = read_ints()
X, V = read_col(N)






def ret_ans1(X, V):  
    sum_v = 0
    ans = -1
    for x, v in zip(X, V):
        sum_v += v
        ans = max(ans, sum_v - x)
    return ans


def ret_ans2(X, V):  
    Z = []
    sum_v = 0
    for x, v in zip(X, V):
        sum_v += v
        Z.append(sum_v - 2 * x)

    Y = []
    sum_v = 0
    for x, v in reversed(list(zip(X, V))):
        sum_v += v
        Y.append(sum_v - (C - x))
    Y = list(reversed(Y))

    
    ans = max_sum(Z, Y)
    return ans


def max_sum(X, Y):
    
    X_accum = [-10**15]
    for x in X:
        X_accum.append(max(x, X_accum[-1]))

    del X_accum[0]

    Y_accum = [-10**15]
    for y in reversed(Y):
        Y_accum.append(max(y, Y_accum[-1]))
    Y_accum = list(reversed(Y_accum))
    del Y_accum[-1]
    ret = 0
    for i in range(len(X) - 1):
        ret = max(ret, X_accum[i] + Y_accum[i + 1])
    return ret


ans = 0
ans = max(ans, ret_ans1(X, V))
ans = max(ans, ret_ans2(X, V))


V = list(reversed(V))
X_r = []
for x in reversed(X):
    X_r.append(C - x)

ans = max(ans, ret_ans1(X_r, V))
ans = max(ans, ret_ans2(X_r, V))
print(ans)

Solution (Python):
N,C = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]
V = [0 for _ in range(N)]
Vm = [0 for _ in range(N)]
V[0] = A[0][1]-A[0][0]
Vm[0] = V[0]
for i in range(1,N):
    V[i] = V[i-1]+A[i][1]-(A[i][0]-A[i-1][0])
    Vm[i] = max(V[i],Vm[i-1])
U = [0 for _ in range(N)]
Um = [0 for _ in range(N)]
U[0] = A[-1][1]-(C-A[-1][0])
Um[0] = U[0]
for j in range(2,N+1):
    U[j-1] = U[j-2]+A[-j][1]-(A[-(j-1)][0]-A[-j][0])
    Um[j-1] = max(U[j-1],Um[j-2])
ans = V[N-1]
for i in range(N-1):
    ans = max(ans,V[i],V[i]-A[i][0]+Um[N-2-i])
ans = max(ans,U[N-1])
for j in range(N-1):
    ans = max(ans,U[j],U[j]-(C-A[-(j+1)][0])+Vm[N-2-j])
print(max(ans,0))

Solution (Python):
n,c=map(int,input().split())
x=[]
v=[]
rightvalue=[]
temp=0
for i in range(n):
  xi,vi=map(int,input().split())
  x.append(xi)
  v.append(vi)
  temp+=vi
  rightvalue.append(temp-xi)
rightmaxdouble=[]
currentmax=0
for i in range(n):
  if currentmax<rightvalue[i]-x[i]:
    currentmax=rightvalue[i]-x[i]
  rightmaxdouble.append(currentmax)
leftvalue=[]
temp=0
for i in range(n):
  temp+=v[n-1-i]
  leftvalue.append(temp-(c-x[n-1-i]))
leftmaxdouble=[]
currentmax=0
for i in range(n):
  if currentmax<leftvalue[i]-(c-x[n-1-i]):
    currentmax=leftvalue[i]-(c-x[n-1-i])
  leftmaxdouble.append(currentmax)
ans=0
for i in range(n):
  if n-i>=2:
    if rightvalue[i]+leftmaxdouble[n-i-2]>ans:
      ans=rightvalue[i]+leftmaxdouble[n-i-2]
  else:
    if rightvalue[i]>ans:
      ans=rightvalue[i]
for i in range(n):
  if n-i>=2:
    if leftvalue[i]+rightmaxdouble[n-i-2]>ans:
      ans=leftvalue[i]+rightmaxdouble[n-i-2]
  else:
    if leftvalue[i]>ans:
      ans=leftvalue[i]
print(ans)

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N,C=MI()
    XV=LLIN(N)
    DP1 = [0]*(N+1)
    DP2 = [0]*(N+1)
    before = 0
    for i,(x,v) in enumerate(XV):
        DP1[i+1]=DP1[i]+v-(abs(x-before))
        before = x
    before = C
    for i,(x,v) in enumerate(XV[::-1]):
        DP2[i+1]=DP2[i]+v-(abs(x-before))
        before = x
    ans = max(max(DP1),max(DP2))
    now = 0

    DP1_ = [d-XV[i][0] for i,d in enumerate(DP1[1:])]
    DP2_ = [d-(C-XV[~i][0]) for i,d in enumerate(DP2[1:])]
    for i in range(N-1):
        if(DP2_[i+1]<DP2_[i]):
            DP2_[i+1] = DP2_[i]
        if(DP1_[i+1]<DP1_[i]):
            DP1_[i+1] = DP1_[i]
    now1 = 0
    now2 = 0
    for i in range(N):
        idx = N-1-i
        
        
        ans = max(ans,DP1[i]+DP2_[idx])
        ans = max(ans,DP2[idx]+DP1_[i])
        
    
    
    
    
    print(ans)

if __name__ == '__main__':
    main()

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

L = [0] * (N + 1)
S = 0
for i, (x, v) in enumerate(XV, start=1):
    S += v
    L[i] = max(L[i - 1], S - x)

R = [0] * (N + 1)
S = 0
for i, (x, v) in enumerate(XV[::-1], start=1):
    S += v
    R[i] = max(R[i - 1], S - (C - x))

ans = max(max(L), max(R))

S = 0
for i, (x, v) in enumerate(XV, start=1):
    S += v
    ans = max(ans, S - 2 * x + R[N - i])

S = 0
for i, (x, v) in enumerate(XV[::-1], start=1):
    S += v
    ans = max(ans, S - (C - x) * 2 + L[N - i])

print(ans)

Solution (Python):


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

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

sushi_2=list(map(lambda x:[x[0]+C, x[1]] , sushi))

sushi+=sushi_2

cal=[[0,0] for i in range(2*N)]

pre_x=C
for i in range(N, 2*N):
    x, v = sushi[i][0], sushi[i][1]
    cal[i][0], cal[i][1] = v-(x-pre_x), v-2*(x-pre_x)
    pre_x=x


pre_x=C
for i in range(N)[::-1]:
    x, v = sushi[i][0], sushi[i][1]
    cal[i][0], cal[i][1] = v-(pre_x-x), v-2*(pre_x-x)
    pre_x=x

left=[[0,0] for i in range(N)]
right=[[0,0] for i in range(N)]

temp_0,temp_1=cal[N][0],cal[N][1]
right[0][0], right[0][1] = max(0,temp_0), max(0,temp_1)
for i in range(N+1,2*N):
    temp_0+=cal[i][0]
    temp_1+=cal[i][1]
    right[i-N][0], right[i-N][1] = max(right[i-N-1][0],temp_0), max(right[i-N-1][1],temp_1)

temp_0,temp_1=cal[N][0],cal[N][1]
right[0][0], right[0][1] = max(0,temp_0), max(0,temp_1)
for i in range(N+1,2*N):
    temp_0+=cal[i][0]
    temp_1+=cal[i][1]
    right[i-N][0], right[i-N][1] = max(right[i-N-1][0],temp_0), max(right[i-N-1][1],temp_1)

temp_0, temp_1=cal[N-1][0], cal[N-1][1]
left[-1][0], left[-1][1] = max(0,temp_0), max(0,temp_1)
for i in range(N-1)[::-1]:
    temp_0+=cal[i][0]
    temp_1+=cal[i][1]
    left[i-N][0], left[i-N][1] = max(left[i-N+1][0],temp_0), max(left[i-N+1][1],temp_1)

"""
print(sushi)
print(cal)
print(right)
print(left)
"""

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

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


print(ans)

Solution (Python):
from itertools import accumulate

n,c = map(int, input().split())
xv = [[0,0]]+[list(map(int, input().split())) for i in range(n)]
xv_rev = [[0,0]]+[[c-x,v] for x,v in xv][:0:-1]
cumsum = [i-x for i,(x,v) in zip(list(accumulate([v for x,v in xv])),xv)]
cumsum_rev = [i-x for i,(x,v) in zip(list(accumulate([v for x,v in xv_rev])),xv_rev)]
xv_max = [0]
xv_rev_max = [0]
now_v = 0
for k,(x,v) in enumerate(xv[:-1],1):
  xv_max.append(max(xv_max[-1], cumsum[k]))
for k,(x,v) in enumerate(xv_rev[:-1],1):
  xv_rev_max.append(max(xv_rev_max[-1], cumsum_rev[k]))
ans = 0
for i,j,(x,v) in zip(xv_max,cumsum_rev[::-1],xv_rev[::-1]):
  ans = max(ans,i+j-x)
for i,j,(x,v) in zip(xv_rev_max,cumsum[::-1],xv[::-1]):
  ans = max(ans,i+j-x)
print(ans)

Solution (Python):







def main():
    N, C = map(int, input().split())
    x = [None] * N
    v = [None] * N
    for i in range(N):
        x[i], v[i] = map(int, input().split())

    cal_clock = [None] * N
    cal = -x[0] + v[0]
    cal_clock[0] = cal if cal > 0 else 0
    for i in range(1, N):
        cal -= x[i] - x[i-1]
        cal += v[i]
        cal_clock[i] = cal if cal > cal_clock[i-1] else cal_clock[i-1]

    cal_anti = [None] * N
    cal = -(C-x[-1]) + v[-1]
    cal_anti[0] = cal if cal > 0 else 0
    for i in range(1, N):
        cal -= x[N-i] - x[N-1-i]
        cal += v[N-1-i]
        cal_anti[i] = cal if cal > cal_anti[i-1] else cal_anti[i-1]

    ans = max(cal_clock[-1], cal_anti[-1])  
    for k in range(N-1):  
        cand_1 = cal_clock[k] - x[k] + cal_anti[N-2-k]
        cand_2 = cal_anti[k] - (C-x[N-1-k]) + cal_clock[N-2-k]
        ans = max(ans, cand_1, cand_2)

    return ans


print(main())

Solution (Python):

import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,C=map(int,input().split())
    x,v=[0]*N,[0]*N
    for i in range(N):
        x[i],v[i]=map(int,input().split())
    ans=0
    S=[0]*(N+1)
    for i in range(N):
        S[i+1]=S[i]+v[i]
    x2=[C-x[N-1-i] for i in range(N)]
    v2=list(reversed(v))
    S2=[0]*(N+1)
    for i in range(N):
        S2[i+1]=S2[i]+v2[i]
    
    MAX=[0]*(N+1)
    for i in range(N):
        MAX[i+1]=max(MAX[i],S[i+1]-x[i])
    MAX2=[0]*(N+1)
    for i in range(N):
        MAX2[i+1]=max(MAX2[i],S2[i+1]-x2[i])
    
    x.append(0)
    x2.append(0)
    for i in range(-1,N):
        ans=max(ans,S2[i+1]-x2[i]*2+MAX[-(i+2)],S[i+1]-x[i]*2+MAX2[-(i+2)])
    print(ans)
        

if __name__ == '__main__':
    main()

Solution (Python):
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n,c = map(int,readline().split())
xv = []
l1 = []
for i in range(n):
    x,v = map(int,readline().split())
    xv.append([x,v])
    l1.append(v)
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])
 
res = max(l1[-1], r1[-1])
for i in range(n-1) :
    res = max(res, l2[i] + r1[n-2-i])
    res = max(res, r2[i] + l1[n-2-i])
    
print(max(res, 0))

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    

    
    

    n,C = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    xv.sort()
    a, b = [], []
    kcal = 0
    for x, v in xv:
        kcal += v
        a.append(kcal - x)
        b.append(kcal-2*x)
    xv.sort(reverse=True)
    c, d = [], []
    kcal = 0
    for x, v in xv:
        kcal += v
        x = C - x
        c.append(kcal - x)
        d.append(kcal-2*x)
    
    for v in [a,b,c,d]:
        for i in range(1, n):
            if v[i] < v[i-1]:
                v[i] = v[i-1]
    
    res = 0
    for i in range(n):
        res = max(res, a[i], c[i])
        if i < n-1:
            res = max(res, b[i]+c[-(i+2)], d[i]+a[-(i+2)])
    print(res)

if __name__ == '__main__':
    main()

Solution (Python):
n,c=map(int,input().split())
X=[]
for i in range(n):
  x,y=map(int,input().split())
  X.append((x,y))
SR,DR=[0]*(n+1),[0]*(n+1)
s,d=0,0
cur=0
for i in range(n):
  x,y=X[i]
  SR[i+1]=SR[i]+y-(x-cur)
  DR[i+1]=DR[i]+y-2*(x-cur)
  cur=x

SL,DL=[0]*(n+1),[0]*(n+1)
s,d=0,0
cur=c
for i in reversed(range(n)):
  x,y=X[i]
  SL[n-i]=SL[n-1-i]+y-(cur-x)
  DL[n-i]=DL[n-1-i]+y-2*(cur-x)
  cur=x

for i in range(n):
  SL[i+1]=max(SL[i+1],SL[i])
  SR[i+1]=max(SR[i+1],SR[i])
ans=0
for i in range(n+1):
  a=max(DR[i]+SL[n-i],DL[i]+SR[n-i])
  ans=max(ans,a)
print(ans)

Solution (Python):
from itertools import accumulate
n,c = map(int,input().split())
wv = [[0,0]]+[list(map(int,input().split())) for i in range(n)]+[[c,0]]
n += 2
ansls = []
ls1 = [0]*n
ls2 = [0]*n
ls3 = [0]*n
ls4 = [0]*n
for i in range(1,n):
  w,v = wv[i]
  w -= wv[i-1][0]
  ls1[i] = v-w*2
  ls2[i] = v-w
for i in range(n-2,-1,-1):
  w,v = wv[i]
  w -= wv[i+1][0]
  ls3[n-i-1] = v+w*2
  ls4[n-i-1] = v+w
als1 = list(accumulate(ls1))
als2 = list(accumulate(ls2))
als3 = list(accumulate(ls3))
als4 = list(accumulate(ls4))
als1 = list(accumulate(als1,max))
als2 = list(accumulate(als2,max))
als3 = list(accumulate(als3,max))
als4 = list(accumulate(als4,max))
for i in range(n-1):
  ansls.append(als1[i]+als4[n-2-i])
  ansls.append(als2[i]+als3[n-2-i])
print(max(ansls))

Solution (Python):

import sys
try:
    from typing import List
except ImportError:
    pass


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    mp1 = [0] * (N + 1)
    mp2 = [0] * (N + 1)
    cum = 0
    for i in range(N):
        cum += v[i]
        mp1[i + 1] = max(mp1[i], cum - x[i])
        mp2[i + 1] = max(mp2[i], cum - x[i] * 2)
    mn1 = [0] * (N + 1)
    mn2 = [0] * (N + 1)
    cum = 0
    for i in reversed(range(N)):
        cum += v[i]
        mn1[i] = max(mn1[i + 1], cum - (C - x[i]))
        mn2[i] = max(mn2[i + 1], cum - (C - x[i]) * 2)

    print(max(
        max(mp1[i] + mn2[i] for i in range(N + 1)),
        max(mp2[i] + mn1[i] for i in range(N + 1)),
    ))


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

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

left = [0] * N
left2 = [0] * N
right = [0] * N
right2 = [0] * N

d = 0
d2 = 0
cal = 0
for i in range(N):
    x, v = sushi[i]
    d = x
    d2 = x * 2
    cal += v
    if i == 0:
        right[i] = max(cal - d, 0)
        right2[i] = max(cal - d2, 0)
    else:
        right[i] = max(cal - d, right[i-1])
        right2[i] = max(cal - d2, right2[i-1])

d = 0
d2 = 0
cal = 0
for i in reversed(range(N)):
    x, v = sushi[i]
    d = C - x
    d2 = (C - x) * 2
    cal += v
    if i == 0:
        left[i] = max(cal - d, 0)
        left2[i] = max(cal - d2, 0)
    else:
        left[i] = max(cal - d, left[i-1])
        left2[i] = max(cal - d2, left[i-1])

ans = 0

for i in range(N):
    if i == 0:
        ans = max(ans, left[i])
    else:
        ans = max(ans, left[i] + right2[i-1])

for i in range(N):
    if i == N - 1:
        ans = max(ans, right[i])
    else:
        ans = max(ans, right[i] + left2[i+1])

print(ans)

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

pre_xn_sum = [ (Xn[0][1] - Xn[0][0]*2,0) ] 
post_xn_sum = []

def get_pre_xn_sum(distance=1):
    pre_xn_sum = [ (Xn[0][1] - Xn[0][0]*distance,0) ] 
    for i in range(1,N):
        cuurent_v = pre_xn_sum[i-1][0] + Xn[i][1] - ( Xn[i][0] - Xn[i-1][0] ) *distance
        previous_max_idx = pre_xn_sum[i-1][1]
        if pre_xn_sum[previous_max_idx][0] > cuurent_v:
            max_idx = previous_max_idx
        else:
            max_idx = i
        pre_xn_sum.append((cuurent_v,max_idx))
    return pre_xn_sum

def get_post_xn_sum(distance=1):
    post_xn_sum = [ (Xn[N-1][1] - (C-Xn[N-1][0])*distance,0) ] 
    for i in range(1,N):
        xn_i = N - 1 - i
        cuurent_v = post_xn_sum[i-1][0] + Xn[xn_i][1] - ( Xn[xn_i+1][0] - Xn[xn_i][0] ) *distance
        previous_max_idx = post_xn_sum[i-1][1]
        if post_xn_sum[previous_max_idx][0] > cuurent_v:
            max_idx = previous_max_idx
        else:
            max_idx = i
        post_xn_sum.append((cuurent_v,max_idx))
    return post_xn_sum

pre_xn_sum = get_pre_xn_sum(1)
pre_xn_sum_2 = get_pre_xn_sum(2)
post_xn_sum = get_post_xn_sum(1)
post_xn_sum_2 = get_post_xn_sum(2)

ans_1 = 0
ans_2 = 0


for i in range(N+1):
    x = i -1
    y = N - 1 - i
    tmp_ans = 0
    if x >= 0:
        x_max_idx = pre_xn_sum[x][1]
        x_max = pre_xn_sum[x_max_idx][0]
        tmp_ans += max(x_max,0)
    if y >= 0:
        y_max_idx = post_xn_sum_2[y][1]
        y_max = post_xn_sum_2[y_max_idx][0]
        tmp_ans += max(y_max,0) 
    ans_1 = max(ans_1,tmp_ans)


for i in range(N+1):
    x = i -1
    y = N - 1 - i
    tmp_ans = 0
    if x >= 0:
        x_max_idx = pre_xn_sum_2[x][1]
        x_max = pre_xn_sum_2[x_max_idx][0]
        tmp_ans += max(x_max,0)
    if y >= 0:
        y_max_idx = post_xn_sum[y][1]
        y_max = post_xn_sum[y_max_idx][0]
        tmp_ans += max(y_max,0) 
    ans_1 = max(ans_1,tmp_ans)

print(max(ans_1,ans_2))

Solution (Python):




import sys
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) 
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


MOD = 10**9 + 7
INF = 2**31  

from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations, accumulate
from bisect import bisect_left, bisect_right  


N, C = read_ints()
X, V = read_col(N)


def solve_max_a_plas_b(A: list, B: list):
    '''max_{i<j}(a_i + b_j)をO(n)で解く'''
    assert len(A) == len(B)
    A_accum = list(accumulate(A, func=max))
    B_accum = list(accumulate(reversed(B), func=max))[::-1]
    ret = 0
    for i in range(len(A_accum) - 1):
        ret = max(A_accum[i] + B_accum[i + 1], ret)
    return ret


def ret_candi(X, V):
    V_accum = list(accumulate(V))
    V_accum_r = list(accumulate(reversed(V)))[::-1]
    A, B = [], []
    katamiti_max = 0  
    for i in range(N):
        katamiti_max = max(katamiti_max, V_accum[i] - X[i])
        A.append(V_accum[i] - 2 * X[i])
        B.append((V_accum_r[i]) - (C - X[i]))
    
    return A, B, katamiti_max


def solve(X, V):
    A, B, katamiti_max = ret_candi(X, V)
    return max(solve_max_a_plas_b(A, B), katamiti_max)


V_r = V[::-1]
X_r = []
for x in reversed(X):
    X_r.append(C - x)
print(max(solve(X, V), solve(X_r, V_r)))

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

dpl=[0 for i in range(n+1)] 
dpr=[0 for i in range(n+1)] 

c=0
for i in  range(n):
    c+=que[i][1]
    dpl[i+1]=c-que[i][0]

d=0
for i in range(1,n+1):
    d+=que[-i][1]
    dpr[i]=d-(C-que[-i][0])

max1=max(dpl)
max2=max(dpr)

dpb_l=[0 for i in range(n+1)]
dpb_r=[0 for i in range(n+1)]

c=0

for i in  range(n):
    c+=que[i][1]
    dpb_l[i+1]=c-2*que[i][0]

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

    dpb_r[i]=d-2*(C-que[-i][0])




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

max3=0

for i in range(1,n):
    max3=max(max3,dpb_l[i]+dpr[n-i],dpb_r[i]+dpl[n-i])

print(max(max1,max2,max3))

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

dpl=[0 for i in range(n+1)] 
dpr=[0 for i in range(n+1)] 

c=0
for i in  range(n):
    c+=que[i][1]
    dpl[i+1]=c-que[i][0]

d=0
for i in range(1,n+1):
    d+=que[-i][1]
    dpr[i]=d-(C-que[-i][0])

max1=max(dpl)
max2=max(dpr)

dpb_l=[0 for i in range(n+1)]
dpb_r=[0 for i in range(n+1)]

c=0

for i in  range(n):
    c+=que[i][1]
    dpb_l[i+1]=c-2*que[i][0]

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

    dpb_r[i]=d-2*(C-que[-i][0])




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

max3=0

for i in range(1,n):
    max3=max(max3,dpb_l[i]+dpr[n-i],dpb_r[i]+dpl[n-i])

print(max(max1,max2,max3))