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())
X_V = [list(map(int, input().split())) for i in range(N)]
max_en = 0
point = [0] * (N+1)
point_back = [0] * (N+1)
point_rev = [0] * (N+1)
point_rev_back = [0] * (N+1)
max_point = [0] * (N+1)
max_point_back = [0] * (N+1)
max_point_rev = [0] * (N+1)
max_point_rev_back = [0] * (N+1)
for i, x_v in enumerate(X_V):
    
    if i == 0:
        point[i+1] = x_v[1] - x_v[0]
        point_back[i+1] = x_v[1] - x_v[0]*2
        point_rev[i+1] = X_V[N-i-1][1] - (C-X_V[N-i-1][0])
        point_rev_back[i+1] = X_V[N-i-1][1] - (C-X_V[N-i-1][0])*2
    else:
        point[i+1] = point[i]+x_v[1] - (x_v[0]-X_V[i - 1][0])
        point_back[i+1] = point[i+1] - x_v[0]
        point_rev[i+1] = point_rev[i]+X_V[N-i-1][1] - (X_V[N-i][0]-X_V[N-i-1][0])
        point_rev_back[i+1] = point_rev[i+1] - (C-X_V[N-i-1][0])

    max_point[i + 1] = max(max_point[i], point[i + 1])
    max_point_back[i + 1] = max(max_point_back[i], point_back[i + 1])
    max_point_rev[i + 1] = max(max_point_rev[i], point_rev[i + 1])
    max_point_rev_back[i + 1] = max(max_point_rev_back[i],
                                    point_rev_back[i + 1])





for i in range(N+1):
    
    max_en = max(max_en, max_point[i], max_point_rev[N-i], max_point_back[i] + max_point_rev[N-i],
                 max_point[i] + max_point_rev_back[N-i])
    
    
    
    
    
    
    
    
    
    
    
    
    

print(max_en)

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

D = []

for i in range(N):
    D.append(list(map(int, input().split())))

R = [[0, 0] for i in range(N + 1)]
cnt = 0
ma = 0
rma = 0
R[0][0] = -1
for i in range(N):
    cnt += D[i][1]
    if cnt - D[i][0] > ma:
        ma = cnt - D[i][0]
    if cnt - D[i][0] * 2 > rma:
        rma = cnt - D[i][0] * 2
    R[i + 1] = [ma, rma]

cnt = 0
Ans = R[N][0]
tmp = 0
for i in range(N - 1, -1, -1):
    cnt += D[i][1]
    tmp = C - D[i][0]
    tmp2 = cnt - tmp * 2 + R[i][0]
    tmp2 = max(tmp2, cnt - tmp + R[i][1])
    if tmp2 > Ans:
        Ans = tmp2

print(Ans)

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

x_list = []
v_list = []
one_list = []
round_list = []
r_one_list = []
r_round_list = []

total = 0

for i in range(n):
    x, v = map(int, input().split())
    x_list.append(x)
    v_list.append(v)
    total = total + v
    one_list.append(total - x)
    round_list.append(total - (2 * x))

prev = 0

for i in range(n):
    if prev > one_list[i]:
        one_list[i] = prev
    else:
        prev = one_list[i]

prev = 0

for i in range(n):
    if prev > round_list[i]:
        round_list[i] = prev
    else:
        prev = round_list[i]


total = 0
for i in range(1, n+1):
    total = total + v_list[-i]
    r_one_list.append(total - (c - x_list[-i]))
    r_round_list.append(total - 2 * (c - x_list[-i]))

prev = 0
for i in range(n):
    if prev > r_one_list[i]:
        r_one_list[i] = prev
    else:
        prev = r_one_list[i]

prev = 0
for i in range(n):
    if prev > r_round_list[i]:
        r_round_list[i] = prev
    else:
        prev = r_round_list[i]

ret = 0

for i in range(n-1):
    tmp = max(one_list[i] + r_round_list[-i-2],
              round_list[i] + r_one_list[-i-2])
    if tmp > ret:
        ret = tmp

ret = max(one_list[-1], r_one_list[-1], ret)

print(ret)

Solution (Python):
def main():
    N, C = map(int, input().split())
    XV = [tuple(map(int, input().split())) for _ in range(N)]
    return max(solve(N, C, XV), solve(N, C, [(C - x, v) for x, v in reversed(XV)]))

def solve(N, C, XV):
    lv = [0] * N
    rv = [0] * N
    x0, c, m = 0, 0, 0
    for i, (x, v) in enumerate(XV):
        c += v - (x - x0)
        m = max(m, c)
        lv[i] = m
        x0 = x
    rv = [0] * N
    x0, c, m = C, 0, 0
    for i, (x, v) in enumerate(reversed(XV)):
        c += v - 2 * (x0 - x)
        m = max(m, c)
        rv[i] = m
        x0 = x
    for i in range(N - 1):
        lv[i] += rv[N - i - 2]
    return max(lv)

print(main())

Solution (Python):

def main():
    N, C = map(int, input().split())
    S = []
    for i in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    r = [S[0][1] - S[0][0]]
    rm = [S[0][1] - S[0][0]]
    for i, v in enumerate(S[1:], start=1):
        r.append(r[-1] + v[1] - (v[0] - S[i-1][0]))
        rm.append(max(rm[-1], r[-1]))
    l = [S[-1][1] + S[-1][0] - C]
    lm = [S[-1][1] + S[-1][0] - C]
    for i, v in enumerate(reversed(S[:-1]), start=1):
        l.append(l[-1] + v[1] - (S[N-i][0] - v[0]))
        lm.append(max(lm[-1], l[-1]))
    l.reverse()
    lm.reverse()
    m = 0
    for i in range(N):
        rr = r[i] - S[i][0] + lm[i+1] if i < N-1 else 0
        ll = l[i] + S[i][0] - C + rm[i-1] if i > 0 else 0
        m = max(m, r[i], rr, ll, l[i])
    return m
print(main())

Solution (Python):

def main():
    N, C = map(int, input().split())
    S = []
    for i in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    r = [S[0][1] - S[0][0]]
    rm = [S[0][1] - S[0][0]]
    for i, v in enumerate(S[1:], start=1):
        r.append(r[-1] + v[1] - (v[0] - S[i-1][0]))
        rm.append(max(rm[-1], r[-1]))
    l = [S[-1][1] + S[-1][0] - C]
    lm = [S[-1][1] + S[-1][0] - C]
    for i, v in enumerate(reversed(S[:-1]), start=1):
        l.append(l[-1] + v[1] - (S[N-i][0] - v[0]))
        lm.append(max(lm[-1], l[-1]))
    l.reverse()
    lm.reverse()
    def func(x,y):
        return max(x, y)
    m = 0
    for i in range(N):
        rr = r[i] - S[i][0] + lm[i+1] if i < N-1 else 0
        ll = l[i] + S[i][0] - C + rm[i-1] if i > 0 else 0
        m = max(m, r[i], rr, ll, l[i])
    return m
print(main())

Solution (Python):
class SegTree:
    def __init__(self, a, func):
        self.n = 2**(len(a) - 1).bit_length()
        self.f = func
        self.d = [0] * (2 * self.n - 1)
        self.d[self.n - 1:self.n - 1 + len(a)] = a
        for i in reversed(range(self.n - 1)):
            self.d[i] = self.f(self.d[2 * i + 1], self.d[2 * i + 2])

    def update(self, i, v):
        i += self.n - 1
        self.d[i] = v
        while i:
            i = (i - 1) // 2
            self.d[i] = self.f(self.d[2 * i + 1], self.d[2 * i + 2])

    def query(self, l, r):
        assert l <= r
        l += self.n
        r += self.n
        s = self.d[l - 1]
        while l < r:
            if l & 1:
                s = self.f(s, self.d[l - 1])
                l += 1
            if r & 1:
                r -= 1
                s = self.f(s, self.d[r - 1])
            l //= 2
            r //= 2
        return s
def main():
    N, C = map(int, input().split())
    S = []
    for i in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    r = [S[0][1] - S[0][0]]
    for i, v in enumerate(S[1:], start=1):
        r.append(r[-1] + v[1] - (v[0] - S[i-1][0]))
    l = [S[-1][1] + S[-1][0] - C]
    for i, v in enumerate(reversed(S[:-1]), start=1):
        l.append(l[-1] + v[1] - (S[N-i][0] - v[0]))
    l.reverse()
    def func(x,y):
        return max(x, y)
    rs = SegTree(r, func)
    ls = SegTree(l, func)
    m = 0
    for i in range(N):
        rr = r[i] - S[i][0] + ls.query(i+1, N) if i < N-1 else 0
        ll = l[i] + S[i][0] - C + rs.query(0, i) if i > 0 else 0
        m = max(m, r[i], rr, ll, l[i])
    return m
print(main())

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

n, c = [int(x) for x in input().split()]
xv = [[0, 0]]
for _ in range(n):
    xv.append([int(x) for x in input().split()])
xv.sort()

from copy import deepcopy

xv_2 = [[0, 0]] + deepcopy(xv)[::-1]
for i in range(1, n + 1):
    xv_2[i][0] = c - xv_2[i][0]

xv_cumsum = [0]
xv_2_cumsum = [0]

for i in range(1, n + 1):
    xv_cumsum.append(xv_cumsum[-1] + xv[i][1])
    xv_2_cumsum.append(xv_2_cumsum[-1] + xv_2[i][1])

clock = [0]
anti_clock = [0]

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

for i in range(1, n + 1):
    anti_clock.append(anti_clock[-1] + xv_2[i][1] - (xv_2[i][0] - xv_2[i - 1][0]))

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

ans = 0

for i in range(n):
    ans = max(ans, xv_2_cumsum[i] - 2*xv_2[i][0] + clock[n - i], xv_cumsum[i] -2*xv[i][0] + anti_clock[n - i])

print(ans)

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [None]*n
    for i in range(n):
        xv[i] = list(map(int, input().split()))
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v = v + vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v = v + vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v = v + vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v = v + vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[i] = left_max
        _2oas[i+1] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1]):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[i] = right_max
        _2obs[i+1] = v - 2*(c - xi)
    for i in range(1, n+1):
        ans = max(ans, _2oas[i-1]+gr[-i], _2obs[i-1]+gl[-i])
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[i] = left_max
        _2oas[i+1] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1]):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[i] = right_max
        _2obs[i+1] = v - 2*(c - xi)
    for i in range(1, n+1):
        oa = gl[-i]
        _2ob = _2obs[i-1]
        ob = gr[-i]
        _2oa = _2oas[i-1]
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[i] = left_max
        _2oas[i+1] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1]):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[i] = right_max
        _2obs[i+1] = v - 2*(c - xi)
    for i in range(1, n+1):
        oa = gl[-i]
        _2ob = _2obs[i-1]
        ob = gr[-i]
        _2oa = _2oas[i-1]
        if ans < _2oa+ob:
            ans = _2oa+ob
        if ans < _2ob+oa:
            ans = _2ob+oa
    print(ans)
        
if __name__ == "__main__":
    main()

Solution (Python):

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

fr1, fr2 = [0 for _ in range(n+1)], [0 for _ in range(n+1)]
fl1, fl2 = [0 for _ in range(n+2)], [0 for _ in range(n+2)]

tmp1, tmp2 = 0, 0
for i in range(0, n):
    tmp1 += v[i+1] - (x[i+1] - x[i])
    tmp2 += v[i+1] - 2 * (x[i+1] - x[i])
    fr1[i+1] = max(tmp1, fr1[i])
    fr2[i+1] = max(tmp2, fr2[i])
    
tmp1, tmp2 = 0, 0
for i in range(n, 0, -1):
    tmp1 += v[i] - abs(x[i+1] - x[i])
    tmp2 += v[i] - 2 * abs(x[i+1] - x[i])
    fl1[i] = max(tmp1, fl1[i+1])
    fl2[i] = max(tmp2, fl2[i+1])

ans = 0
for i in range(n+1):
    ans = max(ans, fr1[i] + fl2[i+1], fr2[i] + fl1[i+1])
print(ans)

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

A1 = [0, 0]
X1 = [0]
A2 = [0, 0]
X2 = [0]
for x, v in xv:
  A1[-1] += v - x
  A1.append(A1[-1] + x)
  X1.append(x)
A1.pop()

xv = xv[::-1]
for x, v in xv:
  A2[-1] += v - (C-x)
  A2.append(A2[-1] + (C-x))
  X2.append(C-x)
A2.pop()

max_1 = []
max_2 = []
now = -1
for i, a in enumerate(A1):
  if a > now:
    max_1.append(i)
    now = a
  else:
    max_1.append(max_1[-1])

now = -1
for i, a in enumerate(A2):
  if a > now:
    max_2.append(i)
    now = a
  else:
    max_2.append(max_2[-1])

ans = 0
for i, a in enumerate(A1):
  idx = max_2[-i-1]
  calory = max(a, a + A2[idx] - X1[i])
  ans = max(ans, calory)

for i, a in enumerate(A2):
  idx = max_1[-i-1]
  calory = max(a, a + A1[idx] - X2[i])
  ans = max(ans, calory)

print(ans)

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

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n,c = na()
migi = []
sushi_m = []

for i in range(n):
  x,v = na()
  migi.append(x)
  sushi_m.append(v)

sushi_h = list(reversed(sushi_m))
hidari = [c-i for i in reversed(migi)]

m = 0
mm = 0
h = 0
hh = 0
mmigi = []
hhidari = []

for i in range(n):
  m += sushi_m[i]
  h += sushi_h[i]
  mm = max(mm,m-migi[i])
  mmigi.append(mm)
  hh = max(hh,h-hidari[i])
  hhidari.append(hh)

ans = 0
for i in range(n):
  if n-i-2 >= 0 and hhidari[n-i-2]-migi[i] > 0:
    ans = max(ans, mmigi[i]+hhidari[n-i-2]-migi[i])
  else:
    ans = max(ans, mmigi[i])
    
for i in range(n):
  if n-i-2 >= 0 and mmigi[n-i-2]-hidari[i] > 0:
    ans = max(ans, hhidari[i]+mmigi[n-i-2]-hidari[i])
  else:
    ans = max(ans, hhidari[i])

print(ans)

Solution (Python):
from itertools import accumulate

import sys

input=sys.stdin.readline

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

acu=list(accumulate(V))
if N>=2:
    data=[0 for i in range(0,N)]
    data[N-1]=acu[N-2]-2*X[N-1]
    for i in range(1,N):
        data[N-1-i]=min(data[N-i],acu[N-2-i]-2*X[N-1-i])

    data2=[0 for i in range(0,N)]
    data2[N-1]=acu[N-2]-X[N-1]
    for i in range(1,N):
        data2[N-1-i]=min(data2[N-i],acu[N-2-i]-X[N-1-i])
    ans=[0 for i in range(0,N-1)]
    for i in range(0,N-1):
        ans[i]=min(data[i+1]-acu[i]+X[i]+2*C,data2[i+1]-acu[i]+2*X[i]+C)
    test1=max(acu[i]-X[i] for i in range(0,N))
    k=sum(V)
    test2=max(k-acu[i]-(C-X[i+1]) for i in range(0,N-1))
    test2=max(test2,k-(C-X[0]))
    test3=k-min(ans)
    print(max(0,test1,test2,test3))
else:
    print(max(0,V[0]-min(C-X[0],X[0])))

Solution (Python):
import sys


class SegmentTree():
    """
    update, get を提供するSegmentTree

    Attributes
    ----------
    __n : int
        葉の数。2 ^ i - 1
    __dot :
        Segment function
    __e: int
        単位元
    __node: list
        Segment Tree
    """
    def __init__(self, A, dot, e):
        """
        Parameters
        ----------
        A : list
            対象の配列
        dot :
            Segment function
        e : int
            単位元
        """
        n = 2 ** (len(A) - 1).bit_length()
        self.__n = n
        self.__dot = dot
        self.__e = e
        self.__node = [e] * (2 * n)
        for i in range(len(A)):
            self.__node[i + n] = A[i]
        for i in range(n - 1, 0, -1):
            self.__node[i] = self.__dot(self.__node[2 * i], self.__node[2 * i + 1])
    
    def update(self, i, c):
        i += self.__n
        node = self.__node
        node[i] = c
        while i > 1:
            i //= 2
            node[i] = self.__dot(node[2 * i], node[2 * i + 1])

    def get(self, l, r):
        vl, vr = self.__e, self.__e
        l += self.__n
        r += self.__n
        while (l < r):
            if l & 1:
                vl = self.__dot(vl, self.__node[l])
                l += 1
            l //= 2
            if r & 1:
                r -= 1
                vr = self.__dot(vr, self.__node[r])
            r //= 2
        return self.__dot(vl, vr)


N, C = map(int, input().split())
S = [tuple(map(int, s.split())) for s in sys.stdin.readlines()]

R = [0] * (N + 1)
pos = 0
for i, (x, v) in enumerate(S):
    R[i + 1] = R[i] + v - (x - pos)
    pos = x
L = [0] * (N + 1)
pos = 0
for i, (x, v) in enumerate(reversed(S)):
    x = C - x
    L[i + 1] = L[i] + v - (x - pos)
    pos = x

RST = SegmentTree(R, max, 0)
LST = SegmentTree(L, max, 0)
ans1 = RST.get(0, N + 1)
ans2 = LST.get(0, N + 1)

score = 0
pos = 0
ans3 = 0
for i in range(N):
    x, v = S[i]
    score += v - (x - pos) * 2
    ans3 = max(ans3, score + LST.get(0, N - i))
    pos = x

score = 0
pos = 0
ans4 = 0
for i in range(N):
    x, v = S[N - 1 - i]
    x = C - x
    score += v - (x - pos) * 2
    ans4 = max(ans4, score + RST.get(0, N - i))
    pos = x


print(max([ans1, ans2, ans3, ans4]))

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

cw = []
cw2 = [0]
v_sm = 0
for x, v in xv:
    v_sm += v
    cw.append(v_sm - x)
    cw2.append(v_sm - 2 * x)

ccw = []
ccw2 = [0]
v_sm = 0
for x, v in xv[::-1]:
    v_sm += v
    ccw.append(v_sm - (c - x))
    ccw2.append(v_sm - 2 * (c - x))

cw_mx = [0]
ccw_mx = [0]
for e in cw:
    cw_mx.append(max(cw_mx[-1], e))
for e in ccw:
    ccw_mx.append(max(ccw_mx[-1], e))

ans = 0
for i, e in enumerate(cw2):
    mx = e + ccw_mx[n-i]
    ans = max(ans, mx)

for i, e in enumerate(ccw2):
    mx = e + cw_mx[n-i]
    ans = max(ans, mx)

print(ans)

Solution (Python):
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, C = MAP()
L = [LIST() for i in range(N)]

A = [0] * N
B = [0] * N

X = []
V = []
for x, v in L:
    X.append(x)
    V.append(v)

tmp_v = 0
for i in range(N):
    tmp_v += V[i]
    A[i] = tmp_v - X[i]

tmp_v = 0
for i in range(N-1, -1, -1):
    tmp_v += V[i]
    B[i] = tmp_v - (C - X[i])

gA = [0] * N
gA[0] = A[0]

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

gB = [0] * N
gB[N-1] = B[N-1]

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

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

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

X,V,M=[0]*(N+1),[0]*(N+1),[0]*(N+1)
for i in range(1,N+1):
  X[i],V[i]=D[i-1][0],V[i-1]+D[i-1][1]
  M[i]=M[i-1] if M[i-1]>V[i]-D[i-1][0] else V[i]-D[i-1][0]

m=0
for i in range(1,N+1):
  e=M[i-1]-(C-X[i]) if M[i-1]>C-X[i] else 0
  e+=V[N]-V[i-1]-(C-X[i])
  m=m if m>e else e

M=[0]*(N+2)
for i in range(N,0,-1):
  p=V[N]-V[i-1]-(C-X[i])
  M[i]=M[i+1] if M[i+1]>p else p

for i in range(1,N+1):
  e=M[i+1]-X[i] if M[i+1]>X[i] else 0
  e+=V[i]-X[i]
  m=m if m>e else e

print(m)

Solution (Python):
import sys
input = sys.stdin.readline
from itertools import product
INF = 10**9
MOD = 10**9 + 7

def main():
    n,c = map(int,input().split())
    sushi = [list(map(int,input().split())) for _ in range(n)]
    
    r = [0] * (n+1)
    l = [0] * (n+1)
    r_max = [0] * (n+1)
    l_max = [0] * (n+1)

    x = 0
    y = c
    for i in range(n):
        r[i+1] = r[i] + sushi[i][1] - sushi[i][0] + x
        r_max[i+1] = max(r_max[i],r[i+1])
        x = sushi[i][0]

        l[-i-2] = l[-i-1] + sushi[-i-1][1] - y + sushi[-i-1][0]
        l_max[-i-2] = max(l_max[-i-1],l[-i-2])
        y = sushi[-i-1][0]
    
    ans = max(r_max[-1], l_max[0])
    for i in range(n-1):
        tmp1 = r[i+1] + l_max[i+1] - sushi[i][0]
        tmp2 = l[i+1] + r_max[i+1] - c + sushi[i+1][0]
        ans = max (ans ,tmp1 ,tmp2 )
    
    print(ans)
  
if __name__=='__main__':
    main()

Solution (Python):
N,C=map(int,input().split())
xc=[tuple(map(int,input().split())) for i in range(N)]
xc.sort()
ans=0
p=0

s=[0]*(N+1)
ss=[0]*(N+1)
for i in range(N):
  s[i+1]=s[i]+xc[i][1]

for i in range(N):
  ss[i+1]=ss[i]+xc[N-1-i][1]
maxs=[0]*(N+1)
maxss=[0]*(N+1)
for i in range(N):
  s[i+1]=s[i+1]-xc[i][0]
  ss[i+1]=ss[i+1]-(C-xc[N-1-i][0])
  maxs[i+1]=max(maxs[i],s[i+1])
  maxss[i+1]=max(maxss[i],ss[i+1])
ans=max(0,maxs[-1])
ans=max(ans,maxss[-1])
for i in range(N):
  if s[i+1]>xc[i][0]:
    ans=max(ans,maxss[N-i-1]+(s[i+1]-xc[i][0]))
  if ss[i+1]>(C-xc[N-1-i][0]):
    ans=max(ans,maxs[N-i-1]+(ss[i+1]-(C-xc[N-1-i][0])))
print(ans)

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

x = [0]*N
v = [0]*N

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

lcal = [0] * N
lmax = [0] * N
rcal = [0] * N
rmax = [0] * N

rcal[0] = v[0]-x[0]
rmax[0] = rcal[0]
for i in range(1,N):
    rcal[i] = rcal[i-1] + v[i] - x[i] + x[i-1]
    rmax[i] = max(rmax[i-1],rcal[i])

lcal[0] = v[N-1] - (C - x[N-1])
lmax[0] = lcal[0]

for i in range(1,N):
    lcal[i] = lcal[i-1] + v[N-i-1] + x[N-i-1] -x[N-i]
    lmax[i] = max(lmax[i-1],lcal[i])




ans = 0

for i in range(N-1):
    ans = max(ans,rcal[i],rcal[i]+lmax[N-i-2]-x[i])
    

ans = max(ans,rcal[N-1])

for i in range(N-1):
    ans = max(ans,lcal[i],lcal[i]+rmax[N-i-2]-(C-x[N-i-1]))
    

ans = max(ans,lcal[N-1])



print(ans)

Solution (Python):
from heapq import heappush, heappop
N, C, *L = map(int, open(0).read().split())
hq1 = []
hq2 = []
sushi = []
for x,y in zip(*[iter(L)]*2):
  sushi += [(x,y)]
sushi.sort()
x = 0
y = 0
for i in range(N-1,-1,-1):
  p,q = sushi[i]
  x += q
  heappush(hq1,(-x+(C-p),i))
  p,q = sushi[N-1-i]
  y += q
  heappush(hq2,(-y+p,N-1-i))
m = 0
ans1 = 0
for i in range(N):
  x,y = sushi[i]
  m += y
  n = m-x
  while hq1 and hq1[0][1]<=i:
    heappop(hq1)
  if hq1 and hq1[0][0]<-x:
    ans1 = max(ans1, n-hq1[0][0]-x)
  else:
    ans1 = max(ans1,n)
    

m = 0
ans2 = 0
for i in range(N-1,-1,-1):
  x,y = sushi[i]
  m += y
  n = m-(C-x)
  while hq2 and hq2[0][1]>=i:
    heappop(hq2)
  if hq2 and hq2[0][0]<-(C-x):
    ans2 = max(ans2, n-hq2[0][0]-(C-x))
  else:
    ans2 = max(ans2, n)
print(max(ans1,ans2))

Solution (Python):
n,c=map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(n)]
acumr=[0,arr[0][1]-arr[0][0]]
acuml=[0,arr[-1][1]-(c-arr[-1][0])]
for i in range(1,n):
  acumr.append(acumr[-1]+arr[i][1]-(arr[i][0]-arr[i-1][0]))
  acuml.append(acuml[-1]+arr[-(i+1)][1]-(arr[-i][0]-arr[-(i+1)][0]))
maxr=[0]
maxl=[0]
for i in range(1,n+1):
  maxr.append(max(maxr[-1],acumr[i]))
  maxl.append(max(maxl[-1],acuml[i]))
ans=0
for i in range(1,n+1):
  tmp1=acumr[i]
  tmp2=acuml[i]
  if arr[i-1][0]<maxl[n-i]:
    tmp1+=maxl[n-i]-arr[i-1][0]
  if c-arr[-i][0]<maxr[n-i]:
    tmp2+=maxr[n-i]-(c-arr[-i][0])
  ans=max(ans,tmp1)
  ans=max(ans,tmp2)
print(ans)

Solution (Python):
N, C = map(int, input().split())
S = [list(map(int, input().split())) for _ in range(N)]
SV = [0]
for x, v in S:
    SV.append(v+SV[-1])
left = [0]
leftturn = [0]
for i in range(N):
    left.append(SV[i+1]-S[i][0])
    leftturn.append(SV[i+1]-S[i][0]*2)
S.reverse()
SV = [0]
for x, v in S:
    SV.append(v+SV[-1])
right = [0]
rightturn = [0]
for i in range(N):
    right.append(SV[i+1]-(C-S[i][0]))
    rightturn.append(SV[i+1]-(C-S[i][0])*2)
ml = [0]
mr = [0]
mlt = [0]
mrt = [0]
for i in range(N):
    ml.append(max(left[i+1], ml[-1]))
    mr.append(max(right[i+1], mr[-1]))
    mlt.append(max(leftturn[i+1], mlt[-1]))
    mrt.append(max(rightturn[i+1], mrt[-1]))
res = 0
for i in range(N+1):
    res = max(res, ml[i]+mrt[N-i], mr[i]+mlt[N-i])
print(res)