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:
N=int(input())
A=[]
dd=0
LL,RR=[],[]

for i in range(N):
  L,R=map(int, input().split())
  LL.append(L)
  RR.append(R)
  A.append((L,-R))
LL=sorted(LL)
RR=sorted(RR)
A=sorted(A)
dl,dr=0,10**9+1
el,er=0,10**9+1
D=[0 for i in range(N-1)]
E=[0 for i in range(N-1)]

for i in range(N-1):
  dl=max(dl,A[i][0])
  dr=min(dr,-A[i][1])
  D[i]=dr-dl+1
  el=max(el,A[-1-i][0])
  er=min(er,-A[-1-i][1])
  E[-i-1]=er-el+1
ans=dd
for i in range(len(D)):
  d=max(0,D[i])+max(0,E[i])
  ans=max(d,ans)
for L,R in A:
  l=LL[-1]
  r=RR[0]
  if LL[0]==L:
    l=LL[-2]
  if RR[0]==R:
    r=RR[1]
  d=(-R-L+1)+max(0,r-l+1)
  ans=max(ans,d)
print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[]
dd=0
for i in range(N):
  L,R=map(int, input().split())
  A.append((L,-R))
  dd=max(dd,R-L+1)
A=sorted(A)
dl,dr=0,10**9+1
el,er=0,10**9+1
D=[0 for i in range(N-1)]
E=[0 for i in range(N-1)]

for i in range(N-1):
  dl=max(dl,A[i][0])
  dr=min(dr,-A[i][1])
  D[i]=dr-dl+1
  el=max(el,A[-1-i][0])
  er=min(er,-A[-1-i][1])
  E[-i-1]=er-el+1
ans=dd
for i in range(len(D)):
  d=max(0,D[i])+max(0,E[i])
  ans=max(d,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[]
for i in range(N):
  L,R=map(int, input().split())
  A.append((L,-R))
A=sorted(A)
dl,dr=0,10**9+1
el,er=0,10**9+1
D=[0 for i in range(N-1)]
E=[0 for i in range(N-1)]
for i in range(N-1):
  dl=max(dl,A[i][0])
  dr=min(dr,-A[i][1])
  D[i]=dr-dl+1
  el=max(el,A[-1-i][0])
  er=min(er,-A[-1-i][1])
  E[-i-1]=er-el+1
ans=0
for i in range(len(D)):
  d=max(0,D[i])+max(0,E[i])
  ans=max(d,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
q=[]
for i in range(n):
  l,r=map(int,input().split())
  q.append((l,r))
q.sort()

lm=[]
rm=[]
lmm=10**10
rmm=10**10
for i in range(n):
  lmm=min(lmm,q[i][1])
  rmm=min(rmm,q[n-i-1][1])
  lm.append(lmm)
  rm.append(rmm)

mx=0
for i in range(n-1):
  t=max(lm[i]-q[i][0]+1,0)+max(rm[n-i-2]-q[-1][0]+1,0)
  mx=max(mx,t)
print(mx)

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 10**18

def main():
    n = int(ipt())
    base = 10**9+1
    query = []
    for i in range(n):
        l,r = map(int,ipt().split())
        query.append(r*base+l)
    query.sort()

    l0 = query[0]%base
    r0 = query[0]//base
    l1 = query[1]%base
    r1 = query[1]//base
    dp0 = [max(l0,l1),min(r0,r1)]
    dp1 = [l0,r0,l1,r1]
    dpv = [dp0[1]-dp0[0]+1,[dp1[1]-dp1[0]+1,dp1[3]-dp1[2]+1]]

    for q in query[2::]:
#        print(dp0,dp1)
        l = q%base
        r = q//base
        d = r-l+1
        dp1[2] = max(dp1[2],l)
        dp1[3] = min(dp1[3],r)
        dpv[1][1] = dp1[3]-dp1[2]+1
        if sum(dpv[1]) < dpv[0]+d:
            dpv[1][0] = dpv[0]
            dpv[1][1] = d
            dp1[0] = dp0[0]
            dp1[1] = dp0[1]
            dp1[2] = l
            dp1[3] = r
        dp0[0] = max(dp0[0],l)
        dp0[1] = min(dp0[1],r)
        dpv[0] = dp0[1]-dp0[0]+1

    print(sum(dpv[1]))




    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

n = int(input())
lrl = []
for _ in range(n):
    l,r = map(int, input().split())
    lrl.append((l,r*(-1)))


lrl.sort()
ansil = [0]*n
c_min_max = 0
c_max_min = 10**10
for i in range(n):
    l,r = lrl[i]
    r *= -1
    c_min_max = l
    c_max_min = min(c_max_min,r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansil[i] = ans


ansilr = [0]*n
c_min_max = lrl[-1][0]
c_max_min = 10**10
for i in range(n-1,-1, -1):
    l,r = lrl[i]
    r *= -1
    c_max_min = min(c_max_min, r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansilr[i] = ans

ans = 0
for i in range(n-1):
    one = ansil[i]
    two = ansilr[i+1]
    ans = max(ans, one+two)

print(ans)

Submission status: Wrong Answer

Solution code:

n = int(input())
lrl = []
lrlr = []
for _ in range(n):
    l,r = map(int, input().split())
    lrl.append((l,r))
    lrlr.append((-r,-l))


lrl.sort()
ansil = [0]*n
c_min_max = 0
c_max_min = 10**10
for i in range(n):
    l,r = lrl[i]
    c_min_max = l
    c_max_min = min(c_max_min,r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansil[i] = ans


ansilr = [0]*n
c_min_max = lrl[-1][0]
c_max_min = 10**10
for i in range(n-1,-1, -1):
    l,r = lrl[i]
    c_max_min = min(c_max_min, r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansilr[i] = ans

ans = 0
for i in range(n-1):
    one = ansil[i]
    two = ansilr[i+1]
    ans = max(ans, one+two)

# print(ans)

# print(ansil)
# print(ansilr)



lrlr.sort()
ansil = [0]*n
c_min_max = 0
c_max_min = 10**10
for i in range(n):
    l,r = lrlr[i]
    c_min_max = l
    c_max_min = min(c_max_min,r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansil[i] = ans


ansilr = [0]*n
c_min_max = lrlr[-1][0]
c_max_min = 10**10
for i in range(n-1,-1, -1):
    l,r = lrlr[i]
    c_max_min = min(c_max_min, r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansilr[i] = ans

# ans = 0
for i in range(n-1):
    one = ansil[i]
    two = ansilr[i+1]
    ans = max(ans, one+two)


print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
lr = [tuple(map(int, input().split())) for _ in range(n)]

mx = 0
mxi = 0
for i in range(n):
    l, r = lr[i]
    if r - l + 1 > mx:
        mx = r - l + 1
        mxi = i

ans = mx
mxl = 0
mnr = 1 << 30
for i in range(n):
    if i == mxi:
        continue
    l, r = lr[i]
    mnr = min(mnr, r)
    mxl = max(mxl, l)

ans += max(0, mnr - mxl + 1)
print(ans)

# 被覆する数の最大値
# 集合の中のmin(0, min(r) - max(l))
#

Submission status: Wrong Answer

Solution code:
n = int(input())
lrl = []
for _ in range(n):
    l,r = map(int, input().split())
    lrl.append((l,r))

lrl.sort()
ansil = [0]*n
c_min_max = 0
c_max_min = 10**10
for i in range(n):
    l,r = lrl[i]
    c_min_max = l
    c_max_min = min(c_max_min,r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansil[i] = ans


ansilr = [0]*n
c_min_max = lrl[-1][0]
c_max_min = 10**10
for i in range(n-1,-1, -1):
    l,r = lrl[i]
    c_max_min = min(c_max_min, r)
    ans = max(0, c_max_min - c_min_max + 1)
    ansilr[i] = ans

ans = 0
for i in range(n-1):
    one = ansil[i]
    two = ansilr[i+1]
    ans = max(ans, one+two)

print(ans)

# print(ansil)
# print(ansilr)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter

class SegTree:  # 0-index !!!
    """
    fx: モノイドXでの二項演算
    ex: モノイドXでの単位元
    init(seq, fx, ex): 配列seqで初期化 O(N)
    update(i, x): i番目の値をxに更新 O(logN)
    query(l, r): 区間[l,r)をfxしたものを返す O(logN)
    get(i): i番目の値を返す
    show(): 配列を返す
    """

    def __init__(self, seq, fx, ex):
        self.n = len(seq)
        self.fx = fx
        self.ex = ex
        self.size = 1<<(self.n - 1).bit_length()
        self.tree = [ex] * (self.size * 2)
        # build
        for i, x in enumerate(seq, start=self.size):
            self.tree[i] = x
        for i in reversed(range(1, self.size)):
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, i, x):  # O(log(n))
        i += self.size
        self.tree[i] = x
        while i:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, i, x):
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, l, r):  # l = r の場合はたぶんバグるので注意
        tmp_l = self.ex
        tmp_r = self.ex
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                tmp_l = self.fx(tmp_l, self.tree[l])
                l += 1
            if r & 1:
                tmp_r = self.fx(self.tree[r - 1], tmp_r)  # 交換法則を仮定しない(順序大事に)
            l >>= 1
            r >>= 1
        return self.fx(tmp_l, tmp_r)

    def get(self, i):
        return self.tree[self.size + i]

    def show(self):
        return self.tree[self.size: self.size + self.n]

# ---------------------- #

n = int(input())
LR = [tuple(int(x) for x in input().split()) for _ in range(n)]
LR.sort(key=itemgetter(1), reverse=True)
LR.sort(key=itemgetter(0))
L = []
R = []
for l, r in LR:
    L.append(l)
    R.append(r + 1)
seg = SegTree(R, fx=min, ex=10**18)
ans = 0
for i in range(1, n - 1):
    contest1 = max(seg.query(0, i) - L[i - 1], 0)
    contest2 = max(seg.query(i, n) - L[n - 1], 0)
    ans = max(ans, contest1 + contest2)
    tmp = max(0, R[i] - L[i] + min(seg.query(0, i), seg.query(i + 1, n)) - L[n - 1])
    ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter

class SegTree:  # 0-index !!!
    """
    fx: モノイドXでの二項演算
    ex: モノイドXでの単位元
    init(seq, fx, ex): 配列seqで初期化 O(N)
    update(i, x): i番目の値をxに更新 O(logN)
    query(l, r): 区間[l,r)をfxしたものを返す O(logN)
    get(i): i番目の値を返す
    show(): 配列を返す
    """

    def __init__(self, seq, fx, ex):
        self.n = len(seq)
        self.fx = fx
        self.ex = ex
        self.size = 1<<(self.n - 1).bit_length()
        self.tree = [ex] * (self.size * 2)
        # build
        for i, x in enumerate(seq, start=self.size):
            self.tree[i] = x
        for i in reversed(range(1, self.size)):
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, i, x):  # O(log(n))
        i += self.size
        self.tree[i] = x
        while i:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, i, x):
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, l, r):  # l = r の場合はたぶんバグるので注意
        tmp_l = self.ex
        tmp_r = self.ex
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                tmp_l = self.fx(tmp_l, self.tree[l])
                l += 1
            if r & 1:
                tmp_r = self.fx(self.tree[r - 1], tmp_r)  # 交換法則を仮定しない(順序大事に)
            l >>= 1
            r >>= 1
        return self.fx(tmp_l, tmp_r)

    def get(self, i):
        return self.tree[self.size + i]

    def show(self):
        return self.tree[self.size: self.size + self.n]

# ---------------------- #

n = int(input())
LR = [tuple(int(x) for x in input().split()) for _ in range(n)]
LR.sort(key=itemgetter(1), reverse=True)
LR.sort(key=itemgetter(0))
L = []
R = []
for l, r in LR:
    L.append(l)
    R.append(r)
seg = SegTree(R, fx=min, ex=10**18)
ans = 0
for i in range(1, n):
    contest1 = max(seg.query(0, i) - L[i - 1] + 1, 0)
    contest2 = max(seg.query(i, n) - L[n - 1] + 1, 0)
    ans = max(ans, contest1 + contest2)
print(ans)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter

class SegTree:  # 0-index !!!
    """
    fx: モノイドXでの二項演算
    ex: モノイドXでの単位元
    init(seq, fx, ex): 配列seqで初期化 O(N)
    update(i, x): i番目の値をxに更新 O(logN)
    query(l, r): 区間[l,r)をfxしたものを返す O(logN)
    get(i): i番目の値を返す
    show(): 配列を返す
    """

    def __init__(self, seq, fx, ex):
        self.n = len(seq)
        self.fx = fx
        self.ex = ex
        self.size = 1<<(self.n - 1).bit_length()
        self.tree = [ex] * (self.size * 2)
        # build
        for i, x in enumerate(seq, start=self.size):
            self.tree[i] = x
        for i in reversed(range(1, self.size)):
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, i, x):  # O(log(n))
        i += self.size
        self.tree[i] = x
        while i:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, i, x):
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, l, r):  # l = r の場合はたぶんバグるので注意
        tmp_l = self.ex
        tmp_r = self.ex
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                tmp_l = self.fx(tmp_l, self.tree[l])
                l += 1
            if r & 1:
                tmp_r = self.fx(self.tree[r - 1], tmp_r)  # 交換法則を仮定しない(順序大事に)
            l >>= 1
            r >>= 1
        return self.fx(tmp_l, tmp_r)

    def get(self, i):
        return self.tree[self.size + i]

    def show(self):
        return self.tree[self.size: self.size + self.n]

# ---------------------- #

n = int(input())
LR = [tuple(int(x) for x in input().split()) for _ in range(n)]
LR.sort(key=itemgetter(0))
L = []
R = []
for l, r in LR:
    L.append(l)
    R.append(r)
seg = SegTree(R, fx=min, ex=10**18)
ans = 0
for i in range(1, n):
    contest1 = max(seg.query(0, i) - L[i - 1] + 1, 0)
    contest2 = max(seg.query(i, n) - L[n - 1] + 1, 0)
    ans = max(ans, contest1 + contest2)
print(ans)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter

class SegTree:  # 0-index !!!
    """
    fx: モノイドXでの二項演算
    ex: モノイドXでの単位元
    init(seq, fx, ex): 配列seqで初期化 O(N)
    update(i, x): i番目の値をxに更新 O(logN)
    query(l, r): 区間[l,r)をfxしたものを返す O(logN)
    get(i): i番目の値を返す
    show(): 配列を返す
    """

    def __init__(self, seq, fx, ex):
        self.n = len(seq)
        self.fx = fx
        self.ex = ex
        self.size = 1<<(self.n - 1).bit_length()
        self.tree = [ex] * (self.size * 2)
        # build
        for i, x in enumerate(seq, start=self.size):
            self.tree[i] = x
        for i in reversed(range(1, self.size)):
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, i, x):  # O(log(n))
        i += self.size
        self.tree[i] = x
        while i:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, i, x):
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, l, r):  # l = r の場合はたぶんバグるので注意
        tmp_l = self.ex
        tmp_r = self.ex
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                tmp_l = self.fx(tmp_l, self.tree[l])
                l += 1
            if r & 1:
                tmp_r = self.fx(self.tree[r - 1], tmp_r)  # 交換法則を仮定しない(順序大事に)
            l >>= 1
            r >>= 1
        return self.fx(tmp_l, tmp_r)

    def get(self, i):
        return self.tree[self.size + i]

    def show(self):
        return self.tree[self.size: self.size + self.n]

# ---------------------- #

n = int(input())
LR = [tuple(int(x) for x in input().split()) for _ in range(n)]
LR.sort(key=itemgetter(0))
L = []
R = []
for l, r in LR:
    L.append(l)
    R.append(r)
seg = SegTree(R, fx=min, ex=10**18)
ans = 0
for i in range(1, n):
    contest1 = seg.query(0, i) - L[i - 1] + 1
    contest2 = seg.query(i, n) - L[n - 1] + 1
    ans = max(ans, contest1 + contest2)
print(ans)

Submission status: Wrong Answer

Solution code:

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

def solve(lr):
    lr.sort(key=lambda x:(x[0],-x[1]))
    N = len(lr)
    right = [0]*N
    left = [0]*N

    r = float('inf')
    for i in reversed(range(N)):
        r = min2(r, lr[i][1])
        right[i] = r
    l = -float('inf')
    for i in reversed(range(N)):
        l = max2(l, lr[i][0])
        left[i] = l

    def it():
        l = -float('inf')
        r = float('inf')
        for i,(a,b) in enumerate(lr[:-1]):
            l = max2(l,a)
            r = min2(r,b)

            x = left[i+1]
            y = right[i+1]
            yield max2(r-l,0)+max2(y-x,0)
    return max(it())



if __name__ == '__main__':
    N = int(input())
    f = lambda x: (int(x[0])-1,int(x[1]))
    lr = [f(input().split()) for _ in range(N)]
    print(solve(lr))

Submission status: Wrong Answer

Solution code:

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

def solve(lr):
    lr.sort()
    N = len(lr)
    right = [0]*N
    left = [0]*N

    r = float('inf')
    for i in reversed(range(N)):
        r = min2(r, lr[i][1])
        right[i] = r
    l = -float('inf')
    for i in reversed(range(N)):
        l = max2(l, lr[i][0])
        left[i] = l

    def it():
        l = -float('inf')
        r = float('inf')
        for i,(a,b) in enumerate(lr[:-1]):
            l = max2(l,a)
            r = min2(r,b)

            x = left[i+1]
            y = right[i+1]
            yield max2(r-l,0)+max2(y-x,0)
    return max(it())



if __name__ == '__main__':
    N = int(input())
    f = lambda x: (int(x[0])-1,int(x[1]))
    lr = [f(input().split()) for _ in range(N)]
    print(solve(lr))

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from operator import itemgetter

    N = int(readline())
    mat = []

    l_max = 0
    r0 = 0
    l_idx = -1
    r_min = INF
    l1 = 0
    r_idx = -1

    for i in range(N):
        l, r = map(int, readline().split())
        r += 1
        mat.append([l, r])
        if l > l_max:
            l_max = l
            r0 = r
            l_idx = i
        if r < r_min:
            l1 = l
            r_min = r
            r_idx = i

    if N == 2:
        ans = 0
        for l, r in mat:
            ans += r - l
        print(ans)
    elif l_idx == r_idx:
        ans = 0
        h = max(0, r_min - l_max)
        for i in range(N):
            l, r = mat[i]
            ans = max(ans, h + r - l)
    else:
        mat2 = []
        for i in range(N):
            l, r = mat[i]
            mat2.append([max(r - l_max, 0), max(r_min - l, 0)])

        mat2.sort(key=itemgetter(1), reverse=True)
        mat2.sort(key=itemgetter(0))

        l_acc = []

        ans = 0
        h = max(0, r_min - l_max)
        for i in range(N):
            l, r = mat[i]
            ans = max(ans, h + r - l)

        a, b = mat2[0][0], r_min - l1
        ans = max(ans, a + b)

        for i in range(N - 1):
            a = max(a, mat2[i + 1][0])
            b = min(b, mat2[i][1])
            ans = max(ans, a + b)

        a, b = r0 - l_max, mat2[N - 1][1]
        ans = max(ans, a + b)

        ans = max(ans, (r0 - l_max))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from operator import itemgetter

    N = int(readline())
    mat = []

    l_max = 0
    r0 = 0
    l_idx = -1
    r_min = INF
    l1 = 0
    r_idx = -1

    for i in range(N):
        l, r = map(int, readline().split())
        r += 1
        mat.append([l, r])
        if l > l_max:
            l_max = l
            r0 = r
            l_idx = i
        if r < r_min:
            l1 = l
            r_min = r
            r_idx = i

    if N == 2:
        ans = 0
        for l, r in mat:
            ans += r - l
        print(ans)
    elif l_idx == r_idx:
        ans = 0
        h = max(0, r_min - l_max)
        for i in range(N):
            l, r = mat[i]
            ans = max(ans, h + r - l)
    else:
        mat2 = []
        for i in range(N):
            l, r = mat[i]
            mat2.append([max(r - l_max, 0), max(r_min - l, 0)])

        mat2.sort(key=itemgetter(1), reverse=True)
        mat2.sort(key=itemgetter(0))

        ans = 0
        h = max(0, r_min - l_max)
        for i in range(N):
            l, r = mat[i]
            ans = max(ans, h + r - l)

        for i in range(N - 1):
            a = mat2[i + 1][0]
            b = mat2[i][1]
            ans = max(ans, a + b)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    N = int(readline())
    mat = []

    for _ in range(N):
        l, r = map(int, readline().split())
        mat.append((l, r))

    l0, r0 = mat[0]

    range_min = INF
    index_min = -1

    for i in range(1, N):
        l_cur, r_cur = mat[i]
        range_cur = max(0, min(r0, r_cur) - max(l0, l_cur))
        if range_cur < range_min:
            index_min = i
            range_min = range_cur

    l1, r1 = mat[index_min]

    for i in range(1, N):
        l_cur, r_cur = mat[i]
        d0 = max(0, l_cur - l0) + max(0, r0 - r_cur)
        d1 = max(0, l_cur - l1) + max(0, r1 - r_cur)
        if d0 > d1:
            l1 = max(l1, l_cur)
            r1 = min(r1, r_cur)
        else:
            l0 = max(l0, l_cur)
            r0 = min(r0, r_cur)

    print(r0 - l0 + r1 - l1 + 2)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
A=[]
B=[]
d={}
dd={}
ans1=0
for i in range(n):
  l,r=map(int,input().split())
  A.append([l+r,l,r])
  B.append(l)
  B.append(r)
  if r-l+1>ans1:
    ans1=r-l+1
A=sorted(A)
B=sorted(B)
for i in range(2*n):
  d[B[i]]=i
  dd[i]=B[i]
E=[0]*(n-1)
F=[0]*(n-1)
AA=[]
for i in range(n):
  AA.append([d[A[i][1]],d[A[i][2]]])
L=-1
R=10**10
for i in range(n-1):
  if L<dd[AA[i][0]]:
    L=dd[AA[i][0]]
  if R>dd[AA[i][1]]:
    R=dd[AA[i][1]]
  E[i]=max(0,R-L+1)
L=-1
R=10**10
for i in range(n-1,0,-1):
  if L<dd[AA[i][0]]:
    L=dd[AA[i][0]]
  if R>dd[AA[i][1]]:
    R=dd[AA[i][1]]
  F[i-1]=max(0,R-L+1)
ans=0
for i in range(n-1):
  p=E[i]+F[i]
  if p>ans:
    ans=p
print(max(ans,ans1))

Submission status: Wrong Answer

Solution code:
n=int(input())
A=[]
B=[]
d={}
dd={}
for i in range(n):
  l,r=map(int,input().split())
  A.append([l+r,l,r])
  B.append(l)
  B.append(r)
A=sorted(A)
B=sorted(B)
for i in range(2*n):
  d[B[i]]=i
  dd[i]=B[i]
E=[0]*(n-1)
F=[0]*(n-1)
AA=[]
for i in range(n):
  AA.append([d[A[i][1]],d[A[i][2]]])
L=-1
R=10**10
for i in range(n-1):
  if L<dd[AA[i][0]]:
    L=dd[AA[i][0]]
  if R>dd[AA[i][1]]:
    R=dd[AA[i][1]]
  E[i]=R-L+1
L=-1
R=10**10
for i in range(n-1,0,-1):
  if L<dd[AA[i][0]]:
    L=dd[AA[i][0]]
  if R>dd[AA[i][1]]:
    R=dd[AA[i][1]]
  F[i-1]=R-L+1
ans=0
for i in range(n-1):
  p=E[i]+F[i]
  if p>ans:
    ans=p
print(ans)

Submission status: Wrong Answer

Solution code:
N, *LR = [int(_) for _ in open(0).read().split()]
LR = sorted(set([(l, r + 1) for l, r in zip(LR[::2], LR[1::2])]))


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


minr = min(r for l, r in LR)
lminr = max(l for l, r in LR if r == minr)
maxl = max(l for l, r in LR)
rmaxl = min(r for l, r in LR if l == maxl)
LR2 = [(lminr, minr)] + [lr for lr in LR if lr != (lminr, minr)]
M = len(LR2)
if M == 1:
    ans = 2 * (LR2[0][1] - LR2[0][0])
elif M == 2:
    ans = sum(r - l for l, r in LR)
else:
    st = SegmentTree([r for l, r in LR2], min, 10**10)
    ans = max(
        max(0,
            st.query(0, i) - max(lminr, LR2[i - 1][0])) +
        max(0,
            st.query(i, M) - LR2[-1][0]) for i in range(1, M - 1))
    ans = max(
        ans,
        max(
            0, minr - maxl + max(r - l for l, r in LR2 if (l, r) not in (
                (maxl, rmaxl), (lminr, minr)))))
print(ans)

Submission status: Wrong Answer

Solution code:
N, *LR = [int(_) for _ in open(0).read().split()]
LR = sorted(set([(l, r + 1) for l, r in zip(LR[::2], LR[1::2])]))


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


minr = min(r for l, r in LR)
lminr = max(l for l, r in LR if r == minr)
maxl = max(l for l, r in LR)
rmaxl = min(r for l, r in LR if l == maxl)
LR2 = [(lminr, minr)] + [lr for lr in LR if lr != (lminr, minr)]
M = len(LR2)
if M == 1:
    ans = 2 * (LR2[0][1] - LR2[0][0])
elif M == 2:
    ans = sum(r - l for l, r in LR)
else:
    st = SegmentTree([r for l, r in LR2], min, 10**10)
    ans = max(
        max(0,
            st.query(0, i) - max(lminr, LR2[i - 1][0])) +
        max(0,
            st.query(i, M) - LR2[-1][0]) for i in range(1, M))
    ans = max(
        ans,
        max(
            0, minr - maxl + max(r - l for l, r in LR2 if (l, r) not in (
                (maxl, rmaxl), (lminr, minr)))))
print(ans)