Problem:


Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931



Sample input:
4
4 7
1 4
5 8
2 5


Sample output:
6

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1

def main():
    inf = 10 ** 10
    n = int(input())
    lr = [list(map(int, input().split())) for _ in range(n)]
    lr.sort(key=lambda x: (x[0], -x[1]))
    r_min_left = [inf] * n
    r_min_right = [inf] * n
    mn = inf
    for i, (l, r) in enumerate(lr):
        if r < mn: mn = r
        r_min_left[i] = mn
    mn = inf
    for i, (l, r) in enumerate(lr[::-1]):
        if r < mn: mn = r
        r_min_right[n - 1 - i] = mn
    ans = 0
    for i in range(n - 1):
        cur = max(0, r_min_left[i] - lr[i][0] + 1) + max(0, r_min_right[i + 1] - lr[-1][0] + 1)
        if cur > ans: ans = cur
    print(ans)

main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.readline

    n = int(input())
    dg = 10**10
    lr = []
    for _ in [0]*n:
        lll,rrr = map(int,input().split())
        lr.append(lll*dg+rrr)
    lr.sort()

    #mirl[i],marl[i]:R0~Riのmin,max
    mirl = [10**10]*n
    marl = [0]*n
    for i,e in enumerate(lr):
        mirl[i] = min(mirl[i-1],e%dg)
        marl[i] = max(marl[i-1],e%dg)
    
    #mirr[i]:Ri~Rn-1のmin
    mirr = [0]*n
    mirr[-1] = lr[-1]%dg
    for i in range(n-2,-1,-1):
        mirr[i] = min(mirr[i+1],lr[i]%dg)

    L1 = lr[-1]//dg
    res = (lr[0]%dg - lr[0]//dg+1) + max(0,mirr[1]-L1+1)

    for k in range(n-2,0,-1):
        #print(res)
        L2 = lr[k]//dg
        R1 = mirr[k+1]
        R2 = lr[k]%dg

        restMaxR = marl[k-1]
        restMinR = mirl[k-1]

        #print(L1,L2,R1,R2,restMaxR,restMinR)

        tmp = max(0,min(restMaxR,R1)-L1+1)+max(0,min(restMinR,R2)-L2+1)
        tmp = max(tmp,max(0,min(restMinR,R1)-L1+1)+max(0,min(restMaxR,R2)-L2+1))
        tmp = max(tmp,max(0,R1-L1+1)+max(0,min(restMinR,R2)-L2+1))
        tmp = max(tmp,max(0,min(restMinR,R1)-L1+1),max(0,R2-L2+1))

        res = max(res,tmp)

    
    print(res)
        



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

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

def quicksort(x):
    if x==[]: return []

    smallerSorted = quicksort([a for a in x[1:] if a[0] < x[0][0] or (a[0] == x[0][0] and a[1] >= x[0][1])])
    biggerSorted = quicksort([a for a in x[1:] if a[0] > x[0][0] or (a[0] == x[0][0] and a[1] < x[0][1])])

    return(smallerSorted+[x[0]]+biggerSorted)

LR = quicksort(LR)

ans = [0] * (n+1)
temp = 10 ** 9
i = 1
for L, R in LR:
    temp = min(temp, R)
    if L > temp:
        break
    ans[i] = temp - L + 1
    i += 1
#print(ans)
temp = 10 ** 9
i = n - 1
L = LR[-1][0]
for x, R in reversed(LR):
    temp = min(temp, R)
    if L > temp:
        break
    ans[i] += temp - L + 1
    i -= 1

#print(LR)
#print(ans)
print(max(ans))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

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

def quicksort(x):
    if x==[]: return []

    smallerSorted = quicksort([a for a in x[1:] if a[0] < x[0][0] or (a[0] == x[0][0] and a[1] >= x[0][0])])
    biggerSorted = quicksort([a for a in x[1:] if a[0] > x[0][0] or (a[0] == x[0][0] and a[1] < x[0][0])])

    return(smallerSorted+[x[0]]+biggerSorted)

LR = quicksort(LR)

ans = [0] * (n+1)
temp = 10 ** 9
i = 1
for L, R in LR:
    temp = min(temp, R)
    if L > temp:
        break
    ans[i] = temp - L + 1
    i += 1
#print(ans)
temp = 10 ** 9
i = n - 1
L = LR[-1][0]
for x, R in reversed(LR):
    temp = min(temp, R)
    if L > temp:
        break
    ans[i] += temp - L + 1
    i -= 1

#print(LR)
#print(ans)
print(max(ans))

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1

def main():
    inf = 10 ** 10
    n = int(input())
    lr = [list(map(int, input().split())) for _ in range(n)]
    lr.sort(key=lambda x: (x[0], x[1]))
    r_min_left = [inf] * n
    r_min_right = [inf] * n
    mn = inf
    for i, (l, r) in enumerate(lr):
        if r < mn: mn = r
        r_min_left[i] = mn
    mn = inf
    for i, (l, r) in enumerate(lr[::-1]):
        if r < mn: mn = r
        r_min_right[n - 1 - i] = mn
    ans = 0
    for i in range(n - 1):
        cur = max(0, r_min_left[i] - lr[i][0] + 1) + max(0, r_min_right[i + 1] - lr[-1][0] + 1)
        if cur > ans: ans = cur
    print(ans)

main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1

def main():
    inf = 10 ** 10
    n = int(input())
    lr = [list(map(int, input().split())) for _ in range(n)]
    lr.sort(key=lambda x: (x[0], x[1]))
    r_min_left = [inf] * n
    r_min_right = [inf] * n
    mn = inf
    for i, (l, r) in enumerate(lr):
        if r < mn: mn = r
        r_min_left[i] = mn
    mn = inf
    for i, (l, r) in enumerate(lr[::-1]):
        if r < mn: mn = r
        r_min_right[n - 1 - i] = mn
    ans = 0
    for i in range(n - 1):
        cur = max(0, r_min_left[i] - lr[i][0]) + max(0, r_min_right[i + 1] - lr[-1][0])
        if cur > ans: ans = cur
    print(ans + 2)

main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1

def main():
    inf = 10 ** 10
    n = int(input())
    lr = [list(map(int, input().split())) for _ in range(n)]
    lr.sort(key=lambda x: (x[0], x[1]))
    r_min_left = [inf] * n
    r_min_right = [inf] * n
    mn = inf
    for i, (l, r) in enumerate(lr):
        if r < mn: mn = r
        r_min_left[i] = mn
    mn = inf
    for i, (l, r) in enumerate(lr[::-1]):
        if r < mn: mn = r
        r_min_right[n - 1 - i] = mn
    ans = 0
    for i in range(n - 1):
        cur = r_min_left[i] - lr[i][0] + r_min_right[i + 1] - lr[-1][0]
        if cur > ans: ans = cur
    print(ans + 2)

main()

Submission status: Wrong Answer

Solution code:
import itertools
from operator import itemgetter

n = int(input())
seikai = []
L_max = 0
R_min = 10 ** 9
for _ in range(n):
  L, R = map(int, input().split(' '))
  if L_max < L:
    L_max = L
  if R_min > R:
    R_min = R
  seikai.append([L, R])

for item in seikai:
  L, R = item
  L_diff = (R - L_max) if (R - L_max) > 0 else 0
  R_diff = (L - R_min) if (L - R_min) > 0 else 0
  item.append(L_diff)
  item.append(R_diff)
# print(n)
# print('seikai: {}'.format(seikai))

# L_diff asc, R_diff desc で sort
tmp_seikai = sorted(seikai, key=itemgetter(3), reverse=True)
# print('tmp_seikai: {}'.format(tmp_seikai))
sorted_seikai = sorted(tmp_seikai, key=itemgetter(2))
# print('sorted_seikai: {}'.format(sorted_seikai))

def calc_fun(count):
  seikai_L = 0
  seikai_R = 10**9
  first_fun = 0
  for i in range(count):
    L, R, L_diff, R_diff = sorted_seikai[i]
    # print('L: {}, R: {}'.format(L, R))
    if seikai_L < L:
      seikai_L = L
    if seikai_R > R:
      seikai_R = R
    
    if seikai_L > seikai_R:
      break
  else:
    first_fun = seikai_R - seikai_L + 1
  
  # 最後の

  seikai_L = 0
  seikai_R = 10**9
  second_fun = 0
  for i in range(count, n):
    L, R, L_diff, R_diff = sorted_seikai[i]
    # print('L: {}, R: {}'.format(L, R))
    if seikai_L < L:
      seikai_L = L
    if seikai_R > R:
      seikai_R = R
    
    if seikai_L > seikai_R:
      break
  else:
    second_fun = seikai_R - seikai_L + 1
  # print('first_fun: {}, second_fun: {}'.format(first_fun, second_fun))
  return first_fun + second_fun

ans = 0
for i in range(1, n):
  # print('i: {}'.format(i))
  fun = calc_fun(i)
  if ans < fun:
    ans = fun

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append([x,y])

ps.sort()
for p in ps:
#    p[1] *= -1
    if p == [mx, my]:
        print(my-mx+1+md)
        sys.exit()

for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break

from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-2):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
#    print(r)
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append([x,-y])

ps.sort()
for p in ps:
    p[1] *= -1
    if p == [mx, my]:
        print(my-mx+1+md)
        sys.exit()

for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break


from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-2):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
#    print(r)
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
N = int(input())

LR = []
for _ in range(N):
    L, R = map(int, input().split())
    LR.append((L, -(R + 1)))

LR.sort()

left = [(0, float('inf'))] * (N + 1)
right = [(0, float('inf'))] * (N + 1)

for i, (l, r) in enumerate(LR, start=1):
    left[i] = (max(left[i - 1][0], l), min(left[i - 1][1], -r))

for i, (l, r) in enumerate(LR[:: -1], start=2):
    right[-i] = (max(right[-i + 1][0], l), min(right[-i + 1][1], -r))

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

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append([x,-y])

ps.sort()
for p in ps:
    p[1] *= -1

if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break


from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-2):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
#    print(r)
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append([x,-y])

ps.sort()
for p in ps:
    p[1] *= -1

if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break


from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-2):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
    print(r)
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

ps.sort()
if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()
for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break


from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-1):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

ps.sort()
for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break

if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-1):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break
ps.sort()

if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0)
#SegTree(pys, N-1, 10**9, min)
for i in range(N-1):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

ps.sort()
if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

from collections import deque
rs = []
dq = deque()
for i in range(1, N):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = 0
#SegTree(pys, N-1, 10**9, min)
for i in range(N-1):
    x = ps[i][0]
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

ps.sort()
if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

from collections import deque
rs = []
dq = deque()
for i in range(1, N):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] > ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = 0
#SegTree(pys, N-1, 10**9, min)
for i in range(N-1):
    x = ps[i][0]
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

class SegTree:
    def __init__(self, init_val, n, ide_ele, seg_func):
        self.segfunc = seg_func
        self.num = 2**(n-1).bit_length()
        self.ide_ele = ide_ele
        self.seg=[self.ide_ele]*2*self.num
        for i in range(n):
            self.seg[i+self.num-1]=init_val[i]    
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfunc(self.seg[2*i+1],self.seg[2*i+2]) 
        
    def update(self, k, x):
        k += self.num-1
        self.seg[k] = x
        while k+1:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self, p, q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfunc(res,self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res,self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res,self.seg[p]),self.seg[q])
        return res


for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

ps.sort()
if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

from collections import deque
rs = []
dq = deque()
for i in range(1, N):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] > ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = 0
#SegTree(pys, N-1, 10**9, min)
y = ps[dq.popleft()][1]
for i in range(N-1):
    x = ps[i][0]
    if len(dq):
        if i+1 == dq[0]:
            #print(dq)
            y = ps[dq.popleft()][1] # mx
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys
from operator import itemgetter, add

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

def compress(A):
    """ 座標圧縮 """

    zipped, unzipped = {}, {}
    for i, a in enumerate(sorted(set(A))):
        zipped[a] = i
        unzipped[i] = a
    return zipped, unzipped

class SegTree:
    """
    セグメント木
    1.update:  i番目の値をxに更新する
    2.query: 区間[l, r)の値を得る
    """

    def __init__(self, n, func, intv, A=[]):
        """
        :param n: 要素数(0-indexed)
        :param func: 値の操作に使う関数(min, max, add, gcdなど)
        :param intv: 要素の初期値(単位元)
        :param A: 初期化に使うリスト(オプション)
        """
        self.n = n
        self.func = func
        self.intv = intv
        # nより大きい2の冪数
        n2 = 1
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [self.intv] * (n2 << 1)
        # 初期化の値が決まっている場合
        if A:
            # 1段目(最下段)の初期化
            for i in range(n):
                self.tree[n2+i] = A[i]
            # 2段目以降の初期化
            for i in range(n2-1, -1, -1):
                self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1])

    def update(self, i, x):
        """
        i番目の値をxに更新
        :param i: index(0-indexed)
        :param x: update value
        """
        i += self.n2
        self.tree[i] = x
        while i > 1:
            self.tree[i >> 1] = x = self.func(x, self.tree[i ^ 1])
            i >>= 1
 
    def query(self, a, b):
        """
        [a, b)の値を得る
        :param a: index(0-indexed)
        :param b: index(0-indexed)
        """
        l = a + self.n2
        r = b + self.n2
        s = self.intv
        while l < r:
            if r & 1:
                r -= 1
                s = self.func(s, self.tree[r])
            if l & 1:
                s = self.func(s, self.tree[l])
                l += 1
            l >>= 1
            r >>= 1
        return s

    def get(self, i):
        """ 一点取得 """
        return self.tree[i+self.n2]

def bisearch_max(mn, mx, func):
    """ 条件を満たす最大値を見つける二分探索 """

    ok = mn
    ng = mx
    while ok+1 < ng:
        mid = (ok+ng) // 2
        if func(mid):
            # 上を探しに行く
            ok = mid
        else:
            # 下を探しに行く
            ng = mid
    return ok

def bisearch_min(mn, mx, func):
    """ 条件を満たす最小値を見つける二分探索 """

    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            # 下を探しに行く
            ok = mid
        else:
            # 上を探しに行く
            ng = mid
    return ok

N = INT()
LR = []
A = set()
for i in range(N):
    l, r = MAP()
    LR.append((l, r))
    A.add(l)
    A.add(r)

zipped, unzipped = compress(A)

LR.sort(key=itemgetter(0))

st1 = SegTree(len(zipped), add, 0)
st2 = SegTree(len(zipped), add, 0)
for i in range(N):
    l, r = LR[i][0], LR[i][1]
    st1.update(zipped[l], st1.get(zipped[l])+1)
    st2.update(zipped[r], st2.get(zipped[r])+1)

def check1(m):
    return st1.query(m, len(zipped)) == 0

def check2(m):
    return st2.query(0, m+1) == 0

def check3(m):
    return st3.query(m, len(zipped)) == 0

def check4(m):
    return st4.query(0, m+1) == 0

ans = 0
# 1区間だけ独立させるケース
for i in range(N):
    l1, r1 = LR[i]
    st1.update(zipped[l1], st1.get(zipped[l1])-1)
    st2.update(zipped[r1], st2.get(zipped[r1])-1)

    idx = bisearch_min(-1, len(zipped), check1) - 1
    l2 = unzipped[idx]
    idx = bisearch_max(0, len(zipped)+1, check2) + 1
    r2 = unzipped[idx]
    ans = max(ans, (r1-l1+1) + (r2-l2+1))

    st1.update(zipped[l1], st1.get(zipped[l1])+1)
    st2.update(zipped[r1], st2.get(zipped[r1])+1)

# ある場所から半分に分けるケース
st3 = SegTree(len(zipped), add, 0)
st4 = SegTree(len(zipped), add, 0)
for i in range(N-1):
    l, r = LR[i]
    st1.update(zipped[l], st1.get(zipped[l])-1)
    st2.update(zipped[r], st2.get(zipped[r])-1)
    st3.update(zipped[l], st3.get(zipped[l])+1)
    st4.update(zipped[r], st4.get(zipped[r])+1)

    idx = bisearch_min(-1, len(zipped), check1) - 1
    l1 = unzipped[idx]
    idx = bisearch_max(0, len(zipped)+1, check2) + 1
    r1 = unzipped[idx]
    idx = bisearch_min(-1, len(zipped), check3) - 1
    l2 = unzipped[idx]
    idx = bisearch_max(0, len(zipped)+1, check4) + 1
    r2 = unzipped[idx]
    ans = max(ans, (r1-l1+1) + (r2-l2+1))

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
sys.setrecursionlimit(10**9)
def input():
    return sys.stdin.readline().rstrip()

def main():
    N=int(input())
    L=[0]*N
    R=[0]*N
    M=0
    maxi=0
    for i in range(N):
        L[i],R[i]=map(int,input().split())
        if M<R[i]-L[i]:
            maxi=i
            M=R[i]-L[i]
    si=np.argsort(L)
    sj=np.argsort(R)
    A=[L[si[N-1]],R[si[N-1]]]
    B=[L[sj[0]],R[sj[0]]] if si[N-1]!=sj[0] else [L[maxi],R[maxi]]
    for i in si:
        a=[max(A[0],L[i]),min(A[1],R[i])]
        b=[max(B[0],L[i]),min(B[1],R[i])]
        if a[1]-a[0]+B[1]-B[0] > b[1]-b[0]+A[1]-A[0]:
            A=a
        else:
            B=b
    x=A[1]-A[0]+B[1]-B[0]+2
    A=[L[si[N-1]],R[si[N-1]]]
    B=[L[maxi],R[maxi]] if si[maxi]!=sj[N-1] else [L[sj[0]],R[sj[0]]]
    for i in si:
        a=[max(A[0],L[i]),min(A[1],R[i])]
        b=[max(B[0],L[i]),min(B[1],R[i])]
        if a[1]-a[0]+B[1]-B[0] > b[1]-b[0]+A[1]-A[0]:
            A=a
        else:
            B=b
    y=A[1]-A[0]+B[1]-B[0]+2
    print(max(x,y))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
sys.setrecursionlimit(10**9)
def input():
    return sys.stdin.readline().rstrip()

def main():
    N=int(input())
    L=[0]*N
    R=[0]*N
    M=0
    maxi=0
    for i in range(N):
        L[i],R[i]=map(int,input().split())
        if M<R[i]-L[i]:
            maxi=i
            M=R[i]-L[i]
    si=np.argsort(L)
    sj=np.argsort(R)
    A=[L[si[N-1]],R[si[N-1]]]
    B=[L[sj[0]],R[sj[0]]] if si[N-1]!=sj[0] else [L[maxi],R[maxi]]
    for i in si:
        a=[max(A[0],L[i]),min(A[1],R[i])]
        b=[max(B[0],L[i]),min(B[1],R[i])]
        if a[1]-a[0]+B[1]-B[0] > b[1]-b[0]+A[1]-A[0]:
            A=a
        else:
            B=b
    print(A[1]-A[0]+B[1]-B[0]+2)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = sorted([list(map(int,input().split())) for _ in range(N)])

com_rng = [[-1,-1] for _ in range(N)]
com_rng[0] = LR[0]
for i in range(1,N):
  com_rng[i][0] = max(com_rng[i-1][0], LR[i][0])
  com_rng[i][1] = min(com_rng[i-1][1], LR[i][1])

com_rng_rev = [[-1,-1] for _ in range(N)]
com_rng_rev[N-1] = LR[N-1]
for i in range(N-1,0,-1):
  com_rng_rev[i-1][0] = max(com_rng_rev[i][0], LR[i-1][0])
  com_rng_rev[i-1][1] = min(com_rng_rev[i][1], LR[i-1][1])
  
ans = 0
for i in range(N-1):
  ans = max(ans, max(com_rng[i][1]-com_rng[i][0]+1,0)+max(com_rng_rev[i+1][1]-com_rng_rev[i+1][0]+1,0))
  #print(i,ans)
  
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = sorted([list(map(int,input().split())) for _ in range(N)])

com_rng = [[-1,-1] for _ in range(N)]
com_rng[0] = LR[0]
for i in range(1,N):
  com_rng[i][0] = max(com_rng[i-1][0], LR[i][0])
  com_rng[i][1] = min(com_rng[i-1][1], LR[i][1])

com_rng_rev = [[-1,-1] for _ in range(N)]
com_rng_rev[N-1] = LR[N-1]
for i in range(N-1,0,-1):
  com_rng_rev[i-1][0] = max(com_rng_rev[i][0], LR[i-1][0])
  com_rng_rev[i-1][1] = min(com_rng_rev[i][1], LR[i-1][1])
  
ans = 0
for i in range(N-1):
  ans = max(ans, com_rng[i][1]-com_rng[i][0]+1+com_rng_rev[i+1][1]-com_rng_rev[i+1][0]+1)
  #print(i,ans)
  
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = sorted([list(map(int,input().split())) for _ in range(N)])

com_rng = [[-1,-1] for _ in range(N)]
com_rng[0] = LR[0]
for i in range(1,N):
  com_rng[i][0] = max(com_rng[i-1][0], LR[i][0])
  com_rng[i][1] = min(com_rng[i-1][1], LR[i][1])

com_rng_rev = [[-1,-1] for _ in range(N)]
com_rng_rev[N-1] = LR[N-1]
for i in range(N-1,0,-1):
  com_rng_rev[i-1][0] = max(com_rng_rev[i][0], LR[i-1][0])
  com_rng_rev[i-1][1] = min(com_rng_rev[i][1], LR[i-1][1])
  
ans = -float('inf')
for i in range(N-1):
  ans = max(ans, com_rng[i][1]-com_rng[i][0]+1+com_rng_rev[i+1][1]-com_rng_rev[i+1][0]+1)
  #print(i,ans)
  
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = sorted([list(map(int,input().split())) for _ in range(N)])

com_rng = [[-1,-1] for _ in range(N)]
com_rng[0] = LR[0]
for i in range(1,N):
  com_rng[i][0] = max(com_rng[i-1][0], LR[i][0])
  com_rng[i][1] = min(com_rng[i-1][1], LR[i][1])

com_rng_rev = [[-1,-1] for _ in range(N)]
com_rng_rev[N-1] = LR[N-1]
for i in range(N-1,0,-1):
  com_rng_rev[i-1][0] = max(com_rng_rev[i][0], LR[i-1][0])
  com_rng_rev[i-1][1] = min(com_rng_rev[i][1], LR[i-1][1])
  
ans = -float('inf')
for i in range(N-1):
  ans = max(ans, max(com_rng[i][1]-com_rng[i][0]+1,0)+max(com_rng_rev[i+1][1]-com_rng_rev[i+1][0]+1,0))
  #print(i,ans)
  
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
x=sorted([tuple(map(int,input().split()))for i in range(n)])


mminfront=[]
m=float("inf")
for s,t in x:
    m=min(m,t)
    mminfront.append(m)

mminback=[]
m=float("inf")
for s,t in x[::-1]:
    m=min(m,t)
    mminback.append(m)
mminback=mminback[::-1]

ans=[]
for i in range(len(x)-1):
    ans.append(max(mminfront[i]-x[i][0],0)+max(mminback[i+1]-x[i+1][0],0))
print(max(ans))