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

def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    l_cum = [[0, 0] for _ in range(N + 1)]
    r_cum = [[0, 0] for _ in range(N + 1)]
    cal = 0
    for i in range(N):
        cal += v[i]
        val = cal - x[i]
        if val > l_cum[i][0]:
            l_cum[i + 1] = [val, x[i]]
        else:
            l_cum[i + 1] = l_cum[i]
    cal = 0
    for i in range(N - 1, -1, -1):
        cal += v[i]
        pos = C - x[i]
        val = cal - pos
        if val > r_cum[i + 1][0]:
            r_cum[i] = [val, pos]
        else:
            r_cum[i] = r_cum[i + 1]
    
    
    ret = 0
    for i in range(N + 1):
        ret = max(ret, l_cum[i][0] + r_cum[i][0] - min(l_cum[i][1], r_cum[i][1]))
    print(ret)
    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):
from itertools import accumulate
N, C = map(int, input().split())

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



R_v = list(accumulate(V))
L_v = list(accumulate(V[::-1]))


R_xv, L_xv = [], []
for i in range(N):
    R_xv.append(R_v[i] - X[i])
    L_xv.append(L_v[i] - (C - X[N - i - 1]))


R_xv_max = list(accumulate(R_xv, func=max))
L_xv_max = list(accumulate(L_xv, func=max))

ans = 0
for i in range(N):
    ans = max(ans, R_xv[i], L_xv[i])
    if i < N - 1:
        ans = max(ans,
                  R_xv[i] - X[i] + L_xv_max[N - i - 2],
                  L_xv[i] - (C - X[N - i - 1]) + R_xv_max[N - i - 2]
                  )

print(ans)

Solution (Python):
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools, random
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right; sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; ansli = []; tmpli = []; candili = []
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]
def mi(n): return [wi() for _ in range(n)]
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]

n, c = wi()
xv = mi(n)

cwli = []; cal = 0
for i in range(n):
    cal += xv[i][1] - xv[i][0]
    if i > 0:
        cal += xv[i - 1][0]
    cwli.append([cal, i])

ccwli = []; cal = 0
for i in range(n - 1, -1, -1):
    cal += xv[i][1] - (c - xv[i][0])
    if i < n - 1:
        cal += (c - xv[i + 1][0])
    ccwli.append([cal, i])

cwli2 = sorted(cwli, reverse=True)
ccwli2 = sorted(ccwli, reverse=True)


nowp = 0

for i in range(n):
    while nowp < n:
        if ccwli2[nowp][1] > i:
            ans = max(cwli[i][0] - xv[i][0] + ccwli2[nowp][0], ans)
            break
        else:
            nowp += 1


nowp = 0
for i in range(n - 1, -1, -1):
    while nowp < n:
        if cwli2[nowp][1] < i:
            ans = max(ccwli[n - i - 1][0] - (c - xv[i][0]) + cwli2[nowp][0], ans)
            break
        else:
            nowp += 1

ans = max(cwli2[0][0], ccwli2[0][0], ans)

print(ans)

Solution (Python):


from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    if y > x // 2:
        y = x - y

    ret = 1

    for i in range(0, y):
        j = x - i
        i = i + 1

        ret = ret * j
        ret = ret // i

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)





def main():
    n, c = intin()
    xvlist = [(0, 0)]
    xvlist.extend(intinl(n))
    xvlist.append((c, 0))

    leftrt = {-1: 0}
    leftmax = {-1: 0}
    rightrt = {-1: 0}
    rightmax = {-1: 0}

    leftxsum = 0
    leftvsum = 0
    rightxsum = 0
    rightvsum = 0

    for i in range(n + 1):
        leftx, leftv = xvlist[i]
        rightx, rightv = xvlist[n-i+1]

        leftxsum = leftx
        leftvsum += leftv
        rightxsum = c - rightx
        rightvsum += rightv

        leftrt[i] = max(leftrt[i-1], leftvsum - leftxsum * 2)
        leftmax[i] = max(leftmax[i-1], leftvsum - leftxsum)
        rightrt[i] = max(rightrt[i-1], rightvsum - rightxsum * 2)
        rightmax[i] = max(rightrt[i-1], rightvsum - rightxsum)

    ans = 0

    for i in range(n + 1):
        ans = max(ans, leftrt[i] + rightmax[n-i])
        ans = max(ans, rightrt[i] + leftmax[n-i])

    print(ans)


if __name__ == '__main__':
    main()

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

cum_col = [0 for _ in range(N+1)]
for i in range(N):
    cum_col[i+1] = cum_col[i] + sushi[i][1]

clockwise_dp = [None for _ in range(N)]
clockwise_best = [0, 0]
anti_clockwise_dp = [None for _ in range(N)]
anti_clockwise_best = [0, 0]
for i in range(N):
    if clockwise_best[0] < cum_col[i+1] - sushi[i][0]:
        clockwise_best = [cum_col[i+1]-sushi[i][0], sushi[i][0]]
    clockwise_dp[i] = clockwise_best

for i in range(N-1, -1, -1):
    if anti_clockwise_best[0] < cum_col[N] - cum_col[i] - C + sushi[i][0]:
        anti_clockwise_best = [
            cum_col[N]-cum_col[i]-C+sushi[i][0],
            C-sushi[i][0]
        ]
    anti_clockwise_dp[i] = anti_clockwise_best

ans = max(clockwise_dp[N-1][0], anti_clockwise_dp[0][0])
for i in range(N-1):
    ans = max(ans,
              clockwise_dp[i][0],
              anti_clockwise_dp[i+1][0],
              clockwise_dp[i][0]+anti_clockwise_dp[i+1][0]-min(clockwise_dp[i][1], anti_clockwise_dp[i+1][1])
              )

print(ans)

Solution (Python):
N, C = map(int, input().split())
D = []
V = [0]

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


L = [0]
for i in range(N):
    L.append(max(L[i], V[i + 1] - D[i]))
L_ = max(L)

R = [0]
for i in range(N):
    R.append(max(R[i], V[N] - V[N - i - 1] - (C - D[-i - 1])))
R_ = max(R)

LR = 0
for i in range(N - 1):
    LR = max(LR, V[i + 1] - D[i] * 2 + R[N - i - 1])


RL = 0
for i in range(N - 1):
    RL = max(RL, V[N] - V[N - i - 1] - (C - D[-i - 1]) * 2 + L[N - i - 1])

print(max(L_, R_, LR, RL))

Solution (Python):
N,C = [ int(it) for it in input().split() ]
li = [ [ int(it) for it in input().split() ] for i in range(N) ]

dx = [0]*(N+1)
for i in range(N+1):
  if (i==0):
    dx[i]=li[i][0]-0
  elif(i==N):
    dx[i]=C-li[i-1][0]
  else:
    dx[i]=li[i][0]-li[i-1][0]

lic = [0]*(N+1)
for i in range(N):
  lic[i+1] = lic[i] + li[i][1] - dx[i]
liu = [0]*(N+1)
for i in range(N,0,-1):
  liu[i-1] = liu[i] + li[i-1][1] - dx[i]
lic2 = [0]*(N+1)
for i in range(N):
  lic2[i+1] = lic2[i] + li[i][1] - dx[i]*2
liu2 = [0]*(N+1)
for i in range(N,0,-1):
  liu2[i-1] = liu2[i] + li[i-1][1] - dx[i]*2
lic2ma = [0]*(N+1)
for i in range(1,N+1):
  lic2ma[i] = max(lic2ma[i-1],lic2[i])
liu2ma = [0]*(N+1)
for i in range(N-1,0,-1):
  liu2ma[i] = max(liu2ma[i+1],liu2[i])

if (False):
  
  print (dx)  
  print ( lic )
  print ( liu )  

  print (lic2)
  print (lic2ma)
  print (liu2)
  print (liu2ma)

ma = 0
for i in range(N+1):
  ma = max(ma, lic[i] + liu2ma[i] )
  ma = max(ma, liu[i] + lic2ma[i] )
  
print ( ma )

Solution (Python):

import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    x = [0] + x
    v = [0] + v

    mx_r = [0]
    for xx, acc in zip(x[1:], accumulate(v[1:], add)):
        mx_r.append(max(acc - xx, mx_r[-1]))

    mx_l = [0]
    for xx, cal in zip(reversed(x), accumulate(reversed(v), add)):
        mx_l.append(max(cal - (C - xx), mx_l[-1]))
    mx_l.reverse()

    ans = 0
    for i in range(N+1):
        ans = max(mx_r[i], mx_r[i] - x[i] + mx_l[i+1], ans)
        if i != 0:
            ans = max(mx_l[i], mx_l[i] - (C - x[i]) + mx_r[i-1], ans)
    return ans


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))
    result = solve(N, C, x, v)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Solution (Python):
N,C = map(int,input().split())
L = []
for i in range(N):
  L.append(list(map(int,input().split())))
A = [0]
B = [0]
k = 0
for i in range(N):
  k += L[i][1]
  p = max(A[i],k-L[i][0])
  A.append(p)
k = 0
for i in range(N):
  k += L[N-i-1][1]
  p = max(B[i],k-(C-L[N-i-1][0]))
  B.append(p)
ans = max(A[N],B[N])
t = 0
for i in range(N):
  b = L[N-i-1][0]
  t += L[N-i-1][1]
  if ans <= t-2*(C-b)+A[N-i-1]:
    ans = t-2*(C-b)+A[N-i-1]
t = 0
for i in range(N):
  a = L[i][0]
  t += L[i][1]
  if ans <= t-2*a+B[N-i-1]:
    ans = t-2*a+B[N-i-1]
print(ans)

Solution (Python):
N,C=map(int,input().split())
IA=[eval(input().replace(" ",","))for _ in range(N)]
MS=[(0,0)]*(N+1)
CS=[0]*(N+1)
RS=0
for i,[a,v] in enumerate(IA):
  CS[i+1]=CS[i]+v
  MS[i+1]=max(CS[i+1]-a,MS[i][0]),max(CS[i+1]-2*a,MS[i][1])
for i in range(N):
  ob=CS[N]-CS[i]
  RS=max(RS,ob+MS[i][0]-2*(C-IA[i][0]),ob+MS[i][1]-(C-IA[i][0]))
print(max(RS,MS[N][0],0))

Solution (Python):
N,C=map(int,input().split())
IA=[[int(i)for i in input().split()]for _ in range(N)]
MS=[(0,0)]*(N+1)
CS=[0]*(N+1)
for i,[a,v] in enumerate(IA):
  CS[i+1]=CS[i]+v
  MS[i+1]=CS[i+1]-a if(CS[i+1]-a)>MS[i][0]else MS[i][0],CS[i+1]-2*a if(CS[i+1]-2*a)>MS[i][1]else MS[i][1]
RS=0
for i in range(N):
  ob=CS[N]-CS[i]
  RS=max(RS,ob+MS[i][0]-2*(C-IA[i][0]),ob+MS[i][1]-(C-IA[i][0]))
print(max(RS, MS[N][0], 0))

Solution (Python):
N,C=map(int, input().split())
IA=[[int(i)for i in input().split()]for _ in range(N)]
MS=[(0,0)]*(N+1)
CS=[0]*(N+1)
for i,[a,v] in enumerate(IA):
    CS[i+1]=CS[i]+v
    MS[i+1]=CS[i+1]-a if(CS[i+1]-a)>MS[i][0]else MS[i][0],CS[i+1]-2*a if(CS[i+1]-2*a)>MS[i][1]else MS[i][1]
res = 0
for i in range(N):
    ob=CS[N]-CS[i]
    res=max(res,ob+MS[i][0]-2*(C-IA[i][0]),ob+MS[i][1]-(C-IA[i][0]))
print(max(res, MS[N][0], 0))

Solution (Python):
N,C=map(int, input().split())
IA=[[int(i) for i in input().split()] for _ in range(N)]
MS=[[0]*(N+1),[0]*(N+1)]
CS=[0]*(N+1)
cum = 0
for i,[a,v] in enumerate(IA):
    cum += v
    MS[0][i+1]=cum-a if(cum-a)>MS[0][i]else MS[0][i]
    MS[1][i+1]=cum-2*a if(cum-2*a)>MS[1][i]else MS[1][i]
    CS[i+1]=cum
res = 0
for i in range(N):
    ob=CS[N]-CS[i]
    res=max(res,ob+MS[0][i]-2*(C-IA[i][0]),ob+MS[1][i]-(C-IA[i][0]))
print(max(res, MS[0][N], 0))

Solution (Python):
N,C=map(int, input().split())
IA=[[int(i) for i in input().split()] for _ in range(N)]
MS=[[(0, 0)]*(N+1),[(0, 0)]*(N+1)]
CS=[0]*(N+1)
cum = 0
for i,[a,v] in enumerate(IA):
    cum += v
    MS[0][i+1]=(cum-a,a)if(cum-a)>MS[0][i][0]else MS[0][i]
    MS[1][i+1]=(cum-2*a,a)if(cum-2*a)>MS[1][i][0]else MS[1][i]
    CS[i+1]=cum
resmax = 0
for i in range(N):
    oasum1, x = MS[0][i]
    oasum2, x = MS[1][i]
    ob = CS[N] - CS[i]
    resmax = max(resmax, ob + oasum1 - 2*(C-IA[i][0]), ob + oasum2 - (C-IA[i][0]))
print(max(resmax, MS[0][N][0], 0))

Solution (Python):
N,C=map(int, input().split())
inarr=[[int(i) for i in input().split()] for _ in range(N)]
maxes=[[(0, 0)]*(N+1),[(0, 0)]*(N+1)]
cums=[0]*(N+1)
cum = 0
for i, [a, v] in enumerate(inarr):
    cum += v
    maxes[0][i+1]=(cum-a,a) if (cum - a) > maxes[0][i][0] else maxes[0][i]
    maxes[1][i+1]=(cum-2*a,a) if (cum - 2*a) > maxes[1][i][0] else maxes[1][i]
    cums[i+1]=cum

resmax = 0
for i, [b, v] in enumerate(inarr):
    oasum1, x = maxes[0][i]
    oasum2, x = maxes[1][i]
    ob = cums[N] - cums[i]
    resmax = max(resmax, ob + oasum1 - 2*(C-b), ob + oasum2 - (C-b))

print(max(resmax, maxes[0][N][0], 0))

Solution (Python):
N,C=map(int, input().split())
inarr=[[int(i) for i in input().split()] for _ in range(N)]
maxes=[[(0, 0)]*N,[(0, 0)]*N]
cums=[0]*(N+1)
cum = 0
cummax1 = (0, 0)
cummax2 = (0, 0)
for i, [a, v] in enumerate(inarr):
    cum += v
    if (cum - a) > cummax1[0]:
        cummax1 = (cum - a, a)
    if (cum - 2*a) > cummax2[0]:
        cummax2 = (cum - 2*a, a)
    maxes[0][i]=cummax1
    maxes[1][i]=cummax2
    cums[i+1]=cum

resmax = 0
for i, [b, v] in enumerate(inarr):
    oasum1, x = (0, 0) if i == 0 else maxes[0][i-1]
    oasum2, x = (0, 0) if i == 0 else maxes[1][i-1]
    ob = cums[N] - cums[i]
    resmax = max(resmax, ob + oasum1 - 2*(C-b), ob + oasum2 - (C-b))

print(max(resmax, maxes[0][N-1][0], 0))

Solution (Python):
N,C=map(int, input().split())
inarr=[[int(i) for i in input().split()] for _ in range(N)]
maxes1=[(0, 0)]*N
maxes2=[(0, 0)]*N
cums=[0]*(N+1)
cum = 0
cummax1 = (0, 0)
cummax2 = (0, 0)
for i, [a, v] in enumerate(inarr):
    cum += v
    if (cum - a) > cummax1[0]:
        cummax1 = (cum - a, a)
    if (cum - 2*a) > cummax2[0]:
        cummax2 = (cum - 2*a, a)
    maxes1[i]=cummax1
    maxes2[i]=cummax2
    cums[i+1]=cum


resmax = 0
for i, [b, v] in enumerate(inarr):
    oasum1, x = (0, 0) if i == 0 else maxes1[i-1]
    oasum2, x = (0, 0) if i == 0 else maxes2[i-1]
    obsum = cums[N] - cums[i]
    resmax = max(resmax, obsum + oasum1 - 2*(C-b), obsum + oasum2 - (C-b))
    


print(max(resmax, maxes1[N-1][0], 0))

Solution (Python):
from collections import Counter, deque
from fractions import gcd
from functools import lru_cache
from functools import reduce
import functools
import heapq
import itertools
import math
import numpy as np
import re
import sys

sys.setrecursionlimit(10000)
INF = float('inf')


def cummax(li, first=-float('inf')):
    """
    累積 max
    :param collections.Iterable li:
    :param float first:
    :return:
    """
    cm = first
    ret = []
    for v in li:
        cm = max(v, cm)
        ret.append(cm)
    return ret


N, C = list(map(int, input().split()))
X, V = zip(*[list(map(int, input().split())) for _ in range(N)])

X = np.array(X)
V = np.array(V)


cs1 = V.cumsum() - X

cm1 = np.array(cummax(cs1, first=0))


cs2 = V[::-1].cumsum() - (C - X)[::-1]

cm2 = np.array(cummax(cs2, first=0))
cs2 = cs2[::-1]
cm2 = cm2[::-1]

ans = max(cm1[-1], cm2[0])

for L in range(len(X) - 1):
    ans = max(ans, cm1[L] + cm2[L + 1] - X[L])

for r in reversed(range(1, len(X))):
    ans = max(ans, cm2[r] + cm1[r - 1] - (C - X[r]))
print(ans)

Solution (Python):
from collections import Counter, deque
from fractions import gcd
from functools import lru_cache
from functools import reduce
import functools
import heapq
import itertools
import math
import numpy as np
import re
import sys

sys.setrecursionlimit(10000)
INF = float('inf')


def cummax(li, first=-float('inf')):
    """
    累積 max
    :param collections.Iterable li:
    :param float first:
    :return:
    """
    cm = first
    ret = []
    for v in li:
        cm = max(v, cm)
        ret.append(cm)
    return ret


N, C = list(map(int, input().split()))
X, V = zip(*[list(map(int, input().split())) for _ in range(N)])

X = np.array(X)
V = np.array(V)


cs1 = V.cumsum() - X

cm1 = np.array(cummax(cs1, first=0))


cs2 = V[::-1].cumsum() - (C - X)[::-1]

cm2 = np.array(cummax(cs2, first=0))
cs2 = cs2[::-1]
cm2 = cm2[::-1]

ans = max(cm1.max(), cm2.max())

r = 0
for L in range(len(X)):
    while r < len(X) and X[r] < X[L] * 2:
        r += 1
    if r < len(X):
        ans = max(ans, cm1[L] + cm2[r] - X[L])
    else:
        break

L = len(X) - 1
for r in reversed(range(len(X))):
    while L >= 0 and X[L] > C - (C - X[r]) * 2:
        L -= 1
    if L >= 0:
        ans = max(ans, cm2[r] + cm1[L] - (C - X[r]))
    else:
        break
print(ans)

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

max_e = 0


e = 0
for x, v in ss:
    e += v
    max_e = max(max_e, e - x)


e = 0
for x, v in ss[::-1]:
    e += v
    max_e = max(max_e, e - (c - x))



clocks = []
e = 0
for x, v in ss:
    e += v
    clocks.append(e - x)

max_clocks = clocks[:]
for i in range(1, len(clocks)):
    max_clocks[i] = max(clocks[i], max_clocks[i-1])

e = 0
for i in range(len(ss) - 1, 0, -1):
    x, v = ss[i]
    e += v
    max_e = max(max_e, e - 2 * (c - x) + max_clocks[i-1])


aclocks = []
e = 0
for x, v in ss[::-1]:
    e += v
    aclocks.append(e - (c - x))

max_aclocks = aclocks[:]
for i in range(1, len(aclocks)):
    max_aclocks[i] = max(aclocks[i], max_aclocks[i-1])

aclocks.reverse()
max_aclocks.reverse()

e = 0
for i in range(len(ss) - 1):
    x, v = ss[i]
    e += v
    max_e = max(max_e, e - 2 * x + max_aclocks[i+1])

print(max_e)

Solution (Python):
def main():
	N, C = map(int, input().split())
	sushi_r = [[0 for _ in range(2)] for _ in range(N+2)]
	sushi_l = [[0 for _ in range(2)] for _ in range(N+2)]
	sushi_r[N+1] = [C, 0]
	sushi_l[N+1] = [C, 0]
	dp_r = [0]*(N+2)
	dp_l = [0]*(N+2)
	ans = 0
	for i in range(1, N+1):
		sushi_r[i] = list(map(int, input().split()))
		sushi_r[i][1] += sushi_r[i-1][1]
		dp_r[i] = max(dp_r[i-1], sushi_r[i][1]-sushi_r[i][0])
	for i in range(1, N+1):
		sushi_l[i][0] = C - sushi_r[N-i+1][0]
		sushi_l[i][1] = sushi_r[N-i+1][1]-sushi_r[N-i][1] + sushi_l[i-1][1]
		dp_l[i] = max(dp_l[i-1], sushi_l[i][1]-sushi_l[i][0])

	for i in range(0, N+1):
		ans = max(ans, dp_l[i]-sushi_l[i][0]+dp_r[N-i])
		ans = max(ans, dp_r[i]-sushi_r[i][0]+dp_l[N-i])

	print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from itertools import accumulate
inf = float('inf')

def acc_max(array):
    na = []
    tmp = 0
    for a in array:
        if a > tmp:
            tmp = a
        na.append(tmp)
    return na

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

right = list(accumulate(V))
left = list(accumulate(V[::-1]))

right1 = [r - x for r, x in zip(right,X)]

left1 = [l - (C-x) for l, x in zip(left,X[::-1])]

right2 = acc_max([r - 2*x for r, x in zip(right,X)])

left2 = acc_max([l - 2*(C-x) for l, x in zip(left,X[::-1])])

ans = 0

for end in range(N):
    if end == N-1:
        res = max(right1[end],left1[end])
    else:
        res = max(right1[end]+left2[N-1-(end+1)],left1[end]+right2[N-1-(end+1)])
    if res > ans:
        ans = res

print(ans)

Solution (Python):
import numpy as np

N,C = list(map(int, input().split()))
XV = [list(map(int, input().split())) for _ in range(N)]
X = np.array([0] + [x for x,v in XV])
V = np.array([0] + [v for x,v in XV])

V_cw_cumsum = V.cumsum()

right_one_ways = V_cw_cumsum - X

V_ccw_cumsum = V[::-1].cumsum()[::-1]

left_one_ways = V_ccw_cumsum - (C-X)

def reduce_each(func, l):
  temp = l.copy()
  for i in range(1,len(l)):
    temp[i] = func(temp[i-1], temp[i])
  return temp


additional_left = np.roll(reduce_each(max, left_one_ways[::-1])[::-1], -1)
additional_left[-1] = 0
right_to_left = V_cw_cumsum - 2*X + additional_left

additional_right = np.roll(reduce_each(max, right_one_ways), 1)
additional_right[0] = 0
left_to_right = V_ccw_cumsum - 2*(C-X) + additional_right

print(max(max(right_one_ways),
          max(left_one_ways),
          max(right_to_left),
          max(left_to_right)))

Solution (Python):
from itertools import accumulate as acc
import sys

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

if N==1: print(max(0, a[0][1]-a[0][0], a[0][1]-(C-a[0][0]) ) ),sys.exit()

tmp=a[0][1]-a[0][0]
M=max(0,tmp)
l=[M]
for i in range(1,N):
    tmp+=a[i][1]-(a[i][0]-a[i-1][0])
    M=max(tmp,M)
    l.append(M)

tmp=a[N-1][1]-(C-a[N-1][0])
M=max(0,tmp)
r=[M]
for i in range(N-2,-1,-1):
    tmp+=a[i][1]-(a[i+1][0]-a[i][0])
    M=max(tmp,M)
    r.append(M)

r.reverse()

ans=max(l[0], r[0], l[0]-a[0][0]+r[1], l[N-1], r[N-1], r[N-1]-(C-a[N-1][0])+l[N-2])

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

print(ans)

Solution (Python):
from itertools import accumulate as acc
import sys

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

if N==1: print(max(0, a[0][1]-a[0][0], a[0][1]-(C-a[0][0]) ) ),sys.exit()

b=list(acc( [ a[i][1] for i in range(N)] ))

ans= sum([a[i][1] for i in range(N)])+max(C-a[0][0],a[N-1][0])

l=[[b[i]-a[i][0],0] for i in range(N)]
r=[[b[N-1]-(C-a[0][0]),0]]+[[b[N-1]-b[i]-(C-a[i+1][0]),0] for i in range(N-1)]

tmp=0
for i in range(N):
    if l[i][0]>tmp: tmp=l[i][0]
    l[i][1]=tmp
tmp=0
for i in range(N-1,-1,-1):
    if r[i][0]>tmp: tmp=r[i][0]
    r[i][1]=tmp

p=[l[0][1],r[0][1],l[0][1]-a[0][0]+r[1][1]]
q=[l[N-1][1],r[N-1][1],r[N-1][0]-(C-a[N-1][0])+l[N-2][1]]

ans=max(p+q)

for i in range(1,N-1):
    p1=l[i][1]
    p2=r[i][1]
    p3=l[i][1]-a[i][0]+r[i+1][1]
    p4=r[i][1]-(C-a[i][0])+l[i-1][1]
    
    ans=max(ans,p1,p2,p3,p4)
    
print(ans)

Solution (Python):
n, c, *t = map(int, open(0).read().split())
right = [0]
left = [0]
sushi = tuple([(0, 0)]) + tuple(zip(t[::2], t[1::2])) + tuple([(c, 0)])
for i in range(1, n + 1):
    x, v = sushi[i]
    y = sushi[i - 1][0]
    cost = right[-1] + v - (x - y)
    right.append(cost)
    x, v = sushi[n + 1 - i]
    y = sushi[n + 2 - i][0]
    cost = left[-1] + v - (y - x)
    left.append(cost)
ans = max(right + left)
right_max = right[:]
left_max = left[:]
for i in range(1, n + 1):
    right_max[i] = max(right_max[i], right_max[i - 1])
    left_max[i] = max(left_max[i], left_max[i - 1])
for i in range(1, n + 1):
    ans = max(ans, \
            right[i] - sushi[i][0] + left_max[n - i], \
            left[i] - c + sushi[n + 1 - i][0] + right_max[n - i])
print(ans)

Solution (Python):
n, c, *t = map(int, open(0).read().split())
right = [0]
left = [0]
sushi = tuple([(0, 0)]) + tuple(zip(t[::2], t[1::2])) + tuple([(c, 0)])
for i in range(1, n + 1):
    x, v = sushi[i]
    y = sushi[i - 1][0]
    cost = right[-1] + v - (x - y)
    right.append(cost)
    x, v = sushi[n + 1 - i]
    y = sushi[n + 2 - i][0]
    cost = left[-1] + v - (y - x)
    left.append(cost)
ans = max(right + left)
right_max = right[:]
left_max = left[:]
for i in range(1, n + 1):
    right_max[i] = max(right_max[i], right_max[i - 1])
    left_max[i] = max(left_max[i], left_max[i - 1])
for i in range(1, n + 1):
    ans = max(ans, \
            right[i] - sushi[i][0] + left_max[n - i], \
            left[i] - c + sushi[n + 1 - i][0] + right_max[n - i])
print(ans)

Solution (Python):
import numpy as np
N, C = map(int, input().split())
XV = [list(map(int, input().split())) for i in range(N)]


V_minus_X = [XV[i][1]-(XV[i][0]-XV[i-1][0])
             for i in range(1, N)]  
V_minus_X.insert(0, XV[0][1]-XV[0][0])
cum_ = np.cumsum(V_minus_X)


V_minus_X_reverse = [XV[i][1]-(XV[i+1][0]-XV[i][0])
                     for i in range(0, N-1)]
V_minus_X_reverse.append(XV[-1][1]-(C-XV[-1][0]))
V_minus_X_reverse.reverse()
cum_reverse = np.cumsum(V_minus_X_reverse)

m_ = []
m_reverse = []
maxim = 0
maxim_reverse = 0
maxim_where = 0
maxim_reverse_where = 0

for i in range(N-1):
    if maxim < cum_[i]:
        maxim = cum_[i]
        maxim_where = XV[i][0]
    if maxim_reverse < cum_reverse[i]:
        maxim_reverse = cum_reverse[i]
        maxim_reverse_where = C - XV[-i - 1][0]
    m_.append((maxim, maxim_where))
    m_reverse.append((maxim_reverse, maxim_reverse_where))

ans = 0

for i in range(N - 1):
    next = m_[i][0] + m_reverse[-i - 1][0] - \
        min(m_[i][1], m_reverse[-i - 1][1])
    ans = max(next, ans)

print(max(ans, max(cum_), max(cum_reverse)))

Solution (Python):
import numpy as np
N, C = map(int, input().split())
XV = [list(map(int, input().split())) for i in range(N)]


V_minus_X = [XV[i][1]-(XV[i][0]-XV[i-1][0])
             for i in range(1, N)]  
V_minus_X.insert(0, XV[0][1]-XV[0][0])
cum_ = np.cumsum(V_minus_X)


V_minus_X_reverse = [XV[i][1]-(XV[i+1][0]-XV[i][0])
                     for i in range(0, N-1)]
V_minus_X_reverse.append(XV[-1][1]-(C-XV[-1][0]))
V_minus_X_reverse.reverse()
cum_reverse = np.cumsum(V_minus_X_reverse)

m_ = []
m_reverse = []
maxim = 0
maxim_reverse = 0
maxim_where = 0
maxim_reverse_where = 0

for i in range(N-1):
    if maxim < cum_[i]:
        maxim = cum_[i]
        maxim_where = XV[i][0]
    if maxim_reverse < cum_reverse[i]:
        maxim_reverse = cum_reverse[i]
        maxim_reverse_where = C - XV[-i - 1][0]
    m_.append((maxim, maxim_where))
    m_reverse.append((maxim_reverse, maxim_reverse_where))

ans = 0

for i in range(N - 1):
    next = m_[i][0] + m_reverse[-i - 1][0] - \
        min(m_[i][1], m_reverse[-i - 1][1])
    
    
    ans = max(next, ans)


print(max(ans, max(cum_), max(cum_reverse)))