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

Solution (Python):


import sys
from operator import itemgetter

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

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
        
        n2 = 1
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [self.intv] * (n2 << 1)
        
        if A:
            
            for i in range(n):
                self.tree[n2+i] = A[i]
            
            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]

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

LR.sort(key=itemgetter(0))
L, R = zip(*LR)
st1 = SegTree(N, max, -INF, L)
st2 = SegTree(N, min, INF, R)

ans = 0

for i in range(N):
    l1 = st1.get(i)
    r1 = st2.get(i)
    l2 = max(st1.query(0, i), st1.query(i+1, N))
    r2 = min(st2.query(0, i), st2.query(i+1, N))
    ans = max(ans, max(r1-l1+1, 0) + max(r2-l2+1, 0))


for i in range(N-1):
    l1 = st1.query(0, i+1)
    r1 = st2.query(0, i+1)
    l2 = st1.query(i+1, N)
    r2 = st2.query(i+1, N)
    ans = max(ans, max(r1-l1+1, 0) + max(r2-l2+1, 0))

print(ans)

Solution (Python):
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 = [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 = [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):
        
        L2 = lr[k]//dg
        R1 = mirr[k+1]
        R2 = lr[k]%dg

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

        

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

Solution (Python):
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:

    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-mx+1, 0) + md
r = max(r, max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0))

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] 
    

    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

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

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from operator import itemgetter

n = ni()
lefts = []
rights = []
intervals = []
for _ in range(n):
    l, r = li()
    r += 1
    lefts.append(l)
    rights.append(r)
    intervals.append((l, r))

maxleft = max(lefts)
minright = min(rights)
ans = 0



longest = 0
for l, r in intervals:
    if l == maxleft or r == minright:
        continue
    else:
        longest = max(longest, r - l)
ans = longest + max(0, minright - maxleft)


intervals = sorted(sorted(intervals, key=itemgetter(1), reverse=True), key=itemgetter(0))

s_maxleft = [intervals[0][0]]
s_minright = [intervals[0][1]]
t_maxleft = [intervals[-1][0]]
t_minright = [intervals[-1][1]]

for idx, (l, r) in enumerate(intervals):
    if idx == 0:
        continue
    s_maxleft.append(max(s_maxleft[-1], l))
    s_minright.append(min(s_minright[-1], r))

for idx, (l, r) in enumerate(intervals[::-1]):
    if idx == 0:
        continue
    t_maxleft.append(max(s_maxleft[-1], l))
    t_minright.append(min(t_minright[-1], r))

t_maxleft = t_maxleft[::-1]
t_minright = t_minright[::-1]

for i in range(n-1):
    ans = max(ans, max(0, s_minright[i] - s_maxleft[i]) + max(0, t_minright[i+1] - t_maxleft[i+1]))

print(ans)

Solution (Python):
N = int(input())
INF = float('inf')

L = []
R = []
for _ in range(N):
    l, r = map(int, input().split())
    L.append(l)
    R.append(r)

maxL = max(L)
minR = min(R)

LR = [(minR - l + 1, r - maxL + 1) for l, r in zip(L, R)]
LR.sort()

ans = 0
S = INF
for (_, b), (a, _) in zip(LR, LR[1:]):
    S = min(S, b)
    ans = max(ans, a + S)


for l, r in zip(L, R):
    now = r - l + 1
    now += max(0, minR - maxL + 1)
    ans = max(ans, now)

print(ans)

Solution (Python):
N = int(input())
LR = []
p = 0
max_L = 0
q = 0
min_R = 10**9 + 1

for i in range(N):
    L, R = map(int, input().split())
    R += 1
    LR.append((L, R))
    if L > max_L:
        p = i
        max_L = L
    if R < min_R:
        q = i
        min_R = R

ans1 = max(R - L for L, R in LR) + max(min_R - max_L, 0)

if N == 2:
    print(sum(R - L for L, R in LR))
    exit()

if p == q:
    print(ans1)
    exit()

L1, R1 = LR[p]
L2, R2 = LR[q]
LR = [(L, R) for i, (L, R) in enumerate(LR) if i != p and i != q]
LR.sort(key=lambda x: (x[1], x[0]), reverse=True)

n = len(LR) + 1
min_sr = [R1] * n
max_tl = [L2] * n

for i in range(1, n):
    min_sr[i] = min(min_sr[i-1], LR[i-1][1])
    max_tl[n-i-1] = max(max_tl[n-i], LR[n-i-1][0])

ans2 = max(max(r - L1, 0) + max(R2 - l, 0) for r, l in zip(min_sr, max_tl))

print(max(ans1, ans2))

Solution (Python):

import sys

def solve(N: int, L: "List[int]", R: "List[int]"):
    LR= list(zip(L,R))
    LR.sort(key=lambda x:x[0])

    r_left_max = [] 
    for lr in LR:
        if r_left_max:
            r_left_max.append(min(r_left_max[-1],lr[1]))
        else:
            r_left_max.append(lr[1])

    r_right_max = []
    for lr in LR[::-1]:
        if r_right_max:
            r_right_max.append(min(r_right_max[-1],lr[1]))
        else:
            r_right_max.append(lr[1])

    answer = 0
    for i in range(1,N):
        a = 0
        a += max(r_left_max[i-1]-LR[i-1][0]+1,0)
        a += max(r_right_max[N-i-1]-LR[-1][0]+1,0)
        answer = max(a,answer)

    
    for i in range(N):
        a =0 
        a+= LR[i][1]-LR[i][0]+1
        if i == N-1:
            min_upper_limit = r_left_max[N-2]
            a+= max(min_upper_limit-LR[N-2][0]+1,0)
        elif i == 0:
            min_upper_limit = r_right_max[N-2]
            a+= max(min_upper_limit-LR[-1][0]+1,0)
        else:
            min_upper_limit = min(r_left_max[i-1],r_right_max[N-i-2])

            a+= max(min_upper_limit-LR[-1][0]+1,0)

        answer = max(a,answer)
    
    print(answer)

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    L = [int()] * (N)  
    R = [int()] * (N)  
    for i in range(N):
        L[i] = int(next(tokens))
        R[i] = int(next(tokens))
    solve(N, L, R)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
from operator import itemgetter as ITEM
input = sys.stdin.readline
N = int(input())
mG = [tuple(map(int, input().split())) for _ in range(N)]

mG.sort(key=ITEM(1), reverse=True)
mG.sort(key=ITEM(0))

INF = 1000100100

vA1 = []
L = -1
R = INF
for l,r in mG[:-1]:
    L = max(L, l)
    R = min(R, r)
    vA1.append(R-L+1)

vA2 = []
L = -1
R = INF
for l,r in mG[:0:-1]:
    L = max(L, l)
    R = min(R, r)
    vA2.append(R-L+1)

M1 = max(a+b for a,b in zip(vA1, vA2[::-1]))



k = 0
idm = -1
for i,(l,r) in enumerate(mG):
    d = r-l+1
    if d > k:
        k = d
        idm = i

L = -1
R = INF
for i,(l,r) in enumerate(mG):
    if i==idm:
        continue
    L = max(L, l)
    R = min(R, r)

M2 = k + max(0, R-L+1)

print(max(M1,M2))

Solution (Python):

n = int(input())
p = sorted(list(map(int, input().split())) for _ in range(n))

lmax = n - 1
rmin = 0
for i in range(n):
    if p[i][1] <= p[rmin][1]:
        rmin = i

ans = 0


dmax = 0
for i in range(n):
    if i == lmax or i == rmin:
        continue
    if p[i][1] - p[i][0] > p[dmax][1] - p[dmax][0]:
        dmax = i
d1 = max(0, p[rmin][1] - p[lmax][0] + 1)
d2 = max(0, p[dmax][1] - p[dmax][0] + 1)
ans = max(ans, d1 + d2)


m = lmax
for i in range(rmin, lmax)[::-1]:
    if p[i + 1][1] < p[m][1]:
        m = i + 1
    d1 = max(0, p[rmin][1] - p[i][0] + 1)
    d2 = max(0, p[m][1] - p[lmax][0] + 1)
    ans = max(ans, d1 + d2)

print(ans)

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

N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
LR.sort(key=itemgetter(0))

dp = [[[0, 0], [0, 0]] for _ in range(N)]

L0, R0 = LR[0]
L1, R1 = LR[1]
dp[1][0][0] = L0
dp[1][0][1] = R0
dp[1][1][0] = L1
dp[1][1][1] = R1
L, R = max(L0, L1), min(R0, R1)
for i in range(1, N-1):
    l, r = LR[i+1]
    a0 = max(min(dp[i][0][1], r) - max(dp[i][0][0], l)+1, 0) + max(dp[i][1][1] - dp[i][1][0] + 1, 0)
    a1 = max(min(dp[i][1][1], r) - max(dp[i][1][0], l)+1, 0) + max(dp[i][0][1] - dp[i][0][0] + 1, 0)
    a2 = max(R-L+1, 0) + r-l+1
    a = max(a0, a1, a2)
    if a == a2:
        dp[i+1][0][0] = l
        dp[i+1][0][1] = r
        dp[i+1][1][0] = L
        dp[i+1][1][1] = R
    elif a == a0:
        dp[i+1][0][0] = max(dp[i][0][0], l)
        dp[i+1][0][1] = min(dp[i][0][1], r)
        dp[i+1][1][0] = dp[i][1][0]
        dp[i+1][1][1] = dp[i][1][1]
    elif a == a1:
        dp[i+1][0][0] = dp[i][0][0]
        dp[i+1][0][1] = dp[i][0][1]
        dp[i+1][1][0] = max(dp[i][1][0], l)
        dp[i+1][1][1] = min(dp[i][1][1], r)
    L, R = max(L, l), min(R, r)

ans = max(dp[N-1][0][1]-dp[N-1][0][0]+1, 0) + max(dp[N-1][1][1] - dp[N-1][1][0] + 1, 0)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
mG = [tuple(map(int, input().split())) for _ in range(N)]

mG.sort(key=lambda x: x[1], reverse=True)
mG.sort(key=lambda x: x[0])



vA1 = []
vL1 = []
vR1 = []
L = -1
R = 10**9 + 1

for l,r in mG[:-1]:
    L = max(L, l)
    R = min(R, r)
    vL1.append(L)
    vR1.append(R)
    vA1.append(R-L+1)



vA2 = []
vL2 = []
vR2 = []
L = -1
R = 10**9 + 1

for l,r in mG[:0:-1]:
    L = max(L, l)
    R = min(R, r)
    vL2.append(L)
    vR2.append(R)
    vA2.append(R-L+1)



M1 = max(a+b for a,b in zip(vA1, vA2[::-1]))



k = 0
idm = -1
for i,(l,r) in enumerate(mG):
    d = r-l+1
    if d > k:
        k = d
        idm = i
    
L = -1
R = 10**9 + 1

for i,(l,r) in enumerate(mG):
    if i==idm:
      continue
    L = max(L, l)
    R = min(R, r)

M2 = k + max(0, R-L+1)

print(max(M1,M2))

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()

def resolve():
    n=int(input())
    I=[tuple(map(int,input().split())) for _ in range(n)]
    I.sort(lambda x:x[1])
    forL=[0]*n
    forL[0]=I[0][0]
    backL=[0]*n
    backL[-1]=I[-1][0]
    for i in range(n-1):
        forL[i+1]=max(forL[i],I[i+1][0])
        backL[-i-2]=max(backL[-i-1],I[-i-2][0])

    def calc1(i): 
        score=0
        score+=max(I[0][1]-forL[i-1]+1,0)
        score+=max(I[i][1]-backL[i]+1,0)
        return score
    ans1=max(calc1(i) for i in range(1,n))

    def calc2(i): 
        score=I[i][1]-I[i][0]+1
        if(0<i<n-1):
            score+=max(I[0][1]-max(forL[i-1],backL[i+1])+1,0)
        elif(i==0):
            score+=max(I[1][1]-max(forL[i-1],backL[i+1])+1,0)
        else:
            score+=max(I[0][1]-forL[i-1]+1,0)
        return score
    ans2=max(calc2(i) for i in range(n))

    print(max(ans1,ans2))
resolve()

Solution (Python):
from operator import itemgetter
N = int(input())
LR = []
for _ in range(N):
    l, r = map(int, input().split())
    LR.append([l, r+1])
ans = 0
for l, r in LR:
    ans = max(ans, r-l)
LR.sort(key=itemgetter(1))


















sch = 0
rr = 0
for l, r in LR:
    if l >= rr:
        rr = r
        sch += 1
if sch >= 3:
    print(ans)
    exit()

mid_range = 0
if sch == 1:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    mid_range = mid_r - mid_l  
    for i in range(N):
        LR[i][1] -= mid_range
    ans += mid_range


LR_ = []
pl = 0
for l, r in LR:
    if pl < l:
        LR_.append([l, r])
        pl = l
LR = LR_
if len(LR) == 1:
    print(ans)
    exit()

Ll, Lr = LR[0]
Rl, Rr = LR[-1][0], LR[1][1]
ans2 = max(Rr-Rl, 0) + Lr-Ll
for i, (l, r) in enumerate(LR[1:-1], 1):
    Ll = l
    Rr = LR[i+1][1]
    ans2 = max(ans2, max(Rr-Rl, 0) + max(Lr-Ll, 0))
ans2 += mid_range * 2
print(max(ans, ans2))

Solution (Python):
from operator import itemgetter
import sys
input = sys.stdin.readline
N = int(input())
LR = []
for _ in range(N):
    l, r = map(int, input().split())
    LR.append([l, r+1])
ans = 0
for l, r in LR:
    ans = max(ans, r-l)

LR.sort(key=itemgetter(1))


sch = 0
rr = 0
for l, r in LR:
    if l >= rr:
        rr = r
        sch += 1
if sch >= 3:
    print(ans)
    exit()

mid_range = 0
if sch == 1:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    mid_range = mid_r - mid_l
    for i in range(N):
        LR[i][1] -= mid_range
    ans += mid_range


LR_ = []
pl = 0
for l, r in LR:
    if pl >= l:
        pass
    else:
        LR_.append([l, r])
        pl = l
LR = LR_
if len(LR) == 1:
    print(ans)
    exit()

Ll, Lr = LR[0]
Rl, Rr = LR[-1][0], LR[1][1]
ans2 = max(Rr-Rl, 0) + Lr-Ll
for i, (l, r) in enumerate(LR[1:-1], 1):
    Ll = l
    Rr = LR[i+1][1]
    ans2 = max(ans2, max(Rr-Rl, 0) + max(Lr-Ll, 0))
ans2 += mid_range * 2
print(max(ans, ans2))

Solution (Python):
from operator import itemgetter
import sys
input = sys.stdin.readline
N = int(input())
LR = []
for _ in range(N):
    l, r = map(int, input().split())
    LR.append([l, r+1])
ans = 0
for l, r in LR:
    ans = max(ans, r - l)

LR.sort(key=itemgetter(1))

sch = 0
rr = 0
for l, r in LR:
    if l >= rr:
        rr = r
        sch += 1

if sch >= 3:
    print(ans)
elif sch == 2:
    
    LR_ = []
    pl = 0
    for l, r in LR:
        if pl >= l:
            pass
        else:
            LR_.append([l, r])
            pl = l
    assert len(LR_) >= 2
    LR = LR_
    Ll, Lr = LR[0]
    Rl, Rr = LR[-1][0], LR[1][1]
    ans = max(ans, max(Rr-Rl, 0) + Lr-Ll)
    for i, (l, r) in enumerate(LR[1:-1], 1):
        Ll = l
        Rr = LR[i+1][1]
        ans = max(ans, max(Rr-Rl, 0) + max(Lr-Ll, 0))
    print(ans)
else:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    for i in range(N):
        LR[i][1] -= mid_r-mid_l
    LR_ = []
    pl = 0
    for l, r in LR:
        if pl >= l:
            pass
        else:
            LR_.append([l, r])
            pl = l
    if not len(LR_) >= 2:
        print(ans + mid_r - mid_l)
        exit()
    assert mid_r - mid_l > 0
    assert LR_ == sorted(LR_)
    an = 0
    LR, LR_ = LR_, LR
    Ll, Lr = LR[0]
    Rl, Rr = LR[-1][0], LR[1][1]
    an = max(an, max(Rr-Rl, 0) + Lr-Ll)
    for i, (l, r) in enumerate(LR[1:-1], 1):
        Ll = l
        Rr = LR[i+1][1]
        an = max(an, max(Rr-Rl, 0) + max(Lr-Ll, 0))
    ans += mid_r - mid_l
    an += (mid_r - mid_l) * 2
    print(max(ans, an))

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
m = map(int,read().split())
LR = list(zip(m,m))

if N==2:
    L1,R1 = LR[0]
    L2,R2 = LR[1]
    answer = (R1-L1+1) + (R2-L2+1)
    print(answer)
    exit()


max_width = max(R-L+1 for L,R in LR)

LR.sort()

INF=10**18

i = -1
opt_R = INF
for n,(L,R) in enumerate(LR):
    if opt_R>=R:
        opt_R=R
        i=n
j = -1
opt_L = -INF
for n,(L,R) in enumerate(LR):
    if opt_L<=L:
        opt_L=L
        j=n

if i==j:
    L,R = LR[i]
    answer = max_width + (R-L+1)
    print(answer)
    exit()

L1,R1 = LR[i]; L2,R2 = LR[j]

LR = [(L,R) for n,(L,R) in enumerate(LR) if n != i and n != j]

LR.sort(key = lambda x: (x[0],-x[1]))

n = len(LR)
dpl = [(-INF,INF)]*(n+1)
dpr = [(-INF,INF)]*(n+1)

for i in range(n):
    a,b = dpl[i]
    L,R = LR[i]
    dpl[i+1] = (max(a,L),min(b,R))
for i in range(n,0,-1):
    a,b = dpr[i]
    L,R = LR[i-1]
    dpr[i-1] = (max(a,L),min(b,R))

answer = 0
for (a,b),(c,d) in zip(dpl,dpr):
    l1 = max(L1,a); r1 = min(R1,b)
    l2 = max(L2,c); r2 = min(R2,d)
    x = max(0,r1-l1+1) + max(0,r2-l2+1)
    if answer < x:
        answer = x

x = max_width + max(0,min(R1,R2)-max(L1,L2)+1)
if answer < x:
    answer = x

print(answer)

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

LR.sort(key=lambda x:[-x[0],x[1]])
ML = LR[0][0]
MR = LR[0][1]
LR.sort(key=lambda x:[x[1],-x[0]])
mR = LR[0][1]
mL = LR[0][0]

ans = max(mR-ML+1,0)
for i in range(N):
    if LR[i] not in [[ML,MR],[mL,mR]]:
        ans = max(ans,max(mR-ML+1,0)+max(LR[i][1]-LR[i][0]+1,0))

LR.sort(key=lambda x:[x[1],x[0]])

L_ = [0]*N
for i in range(N):
    L_[i] = max(LR[i][0],L_[i-1])

for i in range(1,N):
    ans = max(ans,max(LR[i][1]-ML+1,0)+max(mR-L_[i-1]+1,0))

print(ans)

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
m = map(int,read().split())
LR = list(zip(m,m))

if N==2:
    L1,R1 = LR[0]
    L2,R2 = LR[1]
    answer = (R1-L1+1) + (R2-L2+1)
    print(answer)
    exit()


max_width = max(R-L+1 for L,R in LR)

LR.sort()

INF=10**18

i = -1
opt_R = INF
for n,(L,R) in enumerate(LR):
    if opt_R>=R:
        opt_R=R
        i=n
j = -1
opt_L = -INF
for n,(L,R) in enumerate(LR):
    if opt_L<=L:
        opt_L=L
        j=n

if i==j:
    L,R = LR[i]
    answer = max_width + (R-L+1)
    print(answer)
    exit()

L1,R1 = LR[i]; L2,R2 = LR[j]

LR = [(L,R) for n,(L,R) in enumerate(LR) if n != i and n != j]

LR.sort(key = lambda x: (x[0],-x[1]))

n = len(LR)
dpl = [(-INF,INF)]*(n+1)
dpr = [(-INF,INF)]*(n+1)

for i in range(n):
    a,b = dpl[i]
    L,R = LR[i]
    dpl[i+1] = (max(a,L),min(b,R))
for i in range(n,0,-1):
    a,b = dpr[i]
    L,R = LR[i-1]
    dpr[i-1] = (max(a,L),min(b,R))

answer = 0
for (a,b),(c,d) in zip(dpl,dpr):
    l1 = max(L1,a); r1 = min(R1,b)
    l2 = max(L2,c); r2 = min(R2,d)
    x = max(0,r1-l1+1) + max(0,r2-l2+1)
    if answer < x:
        answer = x

x = max_width + max(0,min(R1,R2)-max(L1,L2)+1)
if answer < x:
    answer = x

print(answer)

Solution (Python):
def main():
    n = int(input())
    lr = [list(map(int, input().split())) for _ in [0] * n]
    lr.sort(key=lambda x: (x[0], x[1]))
    min_r = [0] * n
    min_r[0] = lr[0][1]
    min_l = [0] * n
    min_l[n-1] = lr[n-1][1]
    for i in range(1,n):
        min_r[i] = min(min_r[i - 1], lr[i][1])
    for i in range(n-2,-1,-1):
        min_l[i] = min(min_l[i + 1], lr[i][1])
    ans = max([max(min_r[i] - lr[i][0] + 1, 0) + max(min_l[i + 1] - lr[n - 1][0] + 1, 0) for i in range(n - 1)])
    l,r,w=0,10**9+1,0
    for i in range(n):
        l = max(l, lr[i][0])
        r = min(r, lr[i][1])
        w = max(w, lr[i][1] - lr[i][0]+1)
    ans = max(ans, max(r - l + 1, 0) + w)
    print(ans)
main()

Solution (Python):
import sys
n = int(input())
lm, rm = 0, 10**10
seg = []
for _ in range(n):
	l, r = map(int, input().split())
	seg.append([l, r])
	lm = max(lm, l)
	rm = min(rm, r)

seg.sort(key=lambda x: (x[0], x[1]))
mins = [seg[-1][1]]
for i in range(n-2, -1, -1):
	mins.append(min(mins[-1], seg[i][1]))
mins.reverse()

ans = 0
for i in range(n):
	l, r = seg[i]
	if rm < l and r < lm:
		print(max([x[1]-x[0]+1 for x in seg]))
		sys.exit()
	elif lm == l and rm == r:
		print(max(rm-lm+1, 0) + max([x[1]-x[0]+1 for x in seg]))
		sys.exit()
	elif i < n-1:
		ans = max(ans, max(0, rm-l+1) + max(0, mins[i+1]-lm+1))

print(max(ans, max(rm-lm+1, 0) + max([x[1]-x[0]+1 for x in seg])))

Solution (Python):
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
maxlen = int(0)
maxi = 0
N = I()
LR =[[] for _ in range(N)]
LR2 =[]
for i in range(N):
    LR[i] = LI()
    C = LR[i][1] - LR[i][0]
    if C>maxlen:
        maxlen = C
        maxi = i
for i in range(N):
    if not i==maxi:
        LR2.append(LR[i])

LR.sort()
rightend = LR[0][1]
leftend  = LR[N-1][0]

live1 = [[] for _ in range(N)]
live2 = [[] for _ in range(N)]
live1[0] = LR[0]
live2[N-1] = LR[N-1]



cur1 = -1; cur2 = -1
for i in range(1,N):
    if live1[i-1][1]>LR[i][1]:
        rightend = LR[i][1]
    if rightend<LR[i][0]:
        cur1 = i-1
        break
    live1[i] = [max(live1[i-1][0],LR[i][0]),min(live1[i-1][1],LR[i][1])]

for i in range(N-2,-1,-1):
    if live2[i+1][1]<LR[i][0]:
        leftend = LR[i][0]
    if leftend>LR[i][1]:
        cur2 = i+1
        break
    live2[i] = [max(live2[i+1][0],LR[i][0]),min(live2[i+1][1],LR[i][1])]




if cur1==-1:
    cur1=N-2
if cur2==-1:
    cur2=1
ansC = [0]*N
for i in range(cur2,cur1+2):
    ansC[i] = (live1[i-1][1]-live1[i-1][0]+1) + (live2[i][1]-live2[i][0]+1)


LR2.sort()
live3 = LR2[0]
for i in range(1, N - 1):
    live3 = [max(live3[0], LR2[i][0]), min(live3[1], LR2[i][1])]
ansd = live3[1] - live3[0] + 1
anslen = max(ansd, 0) + maxlen+1

ans = max(max(ansC),anslen)




LR.sort(key=lambda x:x[1])
rightend = LR[0][1]
leftend  = LR[N-1][0]

live1 = [[] for _ in range(N)]
live2 = [[] for _ in range(N)]
live1[0] = LR[0]
live2[N-1] = LR[N-1]



cur1 = -1; cur2 = -1
for i in range(1,N):
    if live1[i-1][1]>LR[i][1]:
        rightend = LR[i][1]
    if rightend<LR[i][0]:
        cur1 = i-1
        break
    live1[i] = [max(live1[i-1][0],LR[i][0]),min(live1[i-1][1],LR[i][1])]

for i in range(N-2,-1,-1):
    if live2[i+1][1]<LR[i][0]:
        leftend = LR[i][0]
    if leftend>LR[i][1]:
        cur2 = i+1
        break
    live2[i] = [max(live2[i+1][0],LR[i][0]),min(live2[i+1][1],LR[i][1])]




if cur1==-1:
    cur1=N-2
if cur2==-1:
    cur2=1
ansC = [0]*N
for i in range(cur2,cur1+2):
    ansC[i] = (live1[i-1][1]-live1[i-1][0]+1) + (live2[i][1]-live2[i][0]+1)

LR2.sort(key=lambda x:x[1])
live3 = LR2[0]
for i in range(1, N - 1):
    live3 = [max(live3[0], LR2[i][0]), min(live3[1], LR2[i][1])]
ansd = live3[1] - live3[0] + 1
anslen = max(ansd, 0) + maxlen+1

ans = max(max(ansC),anslen)


print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
LR = [tuple(map(int,input().split())) for i in range(N)]

ltor = {}
rtol = {}
l_dup = set()
r_dup = set()
ans = 0
for i,(l,r) in enumerate(LR):
    ans = max(ans, r-l+1)
    if l in ltor:
        ltor[l] = min(r, ltor[l])
        l_dup.add(l)
    else:
        ltor[l] = r
    if r in rtol:
        rtol[r] = max(l, rtol[r])
        r_dup.add(r)
    else:
        rtol[r] = l
ls = list(ltor.keys())
ls.sort()
rs = list(rtol.keys())
rs.sort(reverse=True)

if ls[-1] <= rs[-1]:
    for l,r in LR:
        maxl = ls[-1] if l!=ls[-1] or l in l_dup else ls[-2]
        minr = rs[-1] if r!=rs[-1] or r in r_dup else rs[-2]
        ans = max(ans, r-l+1 + minr-maxl+1)

ll_ans = [0]
minr = 10**9+10
for l in ls:
    r = ltor[l]
    minr = min(r, minr)
    ll_ans.append(max(0, minr - l + 1))

lr_ans = [0]
maxl = 0
minr = 10**9+10
for l in reversed(ls):
    r = ltor[l]
    minr = min(r, minr)
    maxl = max(l, maxl)
    lr_ans.append(max(0, minr - maxl + 1))
lr_ans.reverse()

rr_ans = [0]
maxl = -10
for r in rs:
    l = rtol[r]
    maxl = max(l, maxl)
    rr_ans.append(max(0, r - maxl + 1))

rl_ans = [0]
minr = 10**9
maxl = -10
for r in reversed(rs):
    l = rtol[r]
    maxl = max(l, maxl)
    minr = min(r, minr)
    rl_ans.append(max(0, minr - maxl + 1))
rl_ans.reverse()

for l,r in list(zip(ll_ans, lr_ans))[1:-1]:
    ans = max(ans, l+r)
for l,r in list(zip(rl_ans, rr_ans))[1:-1]:
    ans = max(ans, l+r)

print(ans)

Solution (Python):

import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


class SegmentTree():
    '''
    非再帰
    segment tree
    '''

    def __init__(self, n, func, init=float('inf')):
        '''
        n->配列の長さ
        func:func(a,b)->val,　func=minだとRMQになる
        木の高さhとすると,
        n:h-1までのノード数。h段目のノードにアクセスするために使う。
        data:ノード。
        parent:k->child k*2+1とk*2+2
        '''
        self.n = 2**(n-1).bit_length()
        self.init = init
        self.data = [init]*(2*self.n)
        self.func = func

    def set(self, k, v):
        '''
        あたいの初期化
        '''
        self.data[k+self.n-1] = v

    def build(self):
        '''
        setの後に一斉更新
        '''
        for k in reversed(range(self.n-1)):
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def update(self, k, a):
        '''
        list[k]=aに更新する。
        更新ぶんをrootまで更新
        '''
        k += self.n-1
        self.data[k] = a

        while k > 0:
            k = (k-1)//2
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def query(self, l, r):
        '''
        [l,r)のfuncを求める
        '''
        L = l+self.n
        R = r+self.n
        ret = self.init
        while L < R:
            if R & 1:
                R -= 1
                ret = self.func(ret, self.data[R-1])
            if L & 1:
                ret = self.func(ret, self.data[L-1])
                L += 1
            L >>= 1
            R >>= 1
        return ret


N = int(input())
L = [list(map(int, input().split())) for _ in range(N)]
L = sorted(L, key=lambda x: x[0])

Seg_L = SegmentTree(N, lambda a, b: max(a, b), init=0)
Seg_R = SegmentTree(N, lambda a, b: min(a, b), init=float('inf'))

for i, q in enumerate(L):
    l, r = q[0], q[1]
    Seg_L.set(i, l)
    Seg_R.set(i, r)
Seg_L.build()
Seg_R.build()
cand = []
for pivot in range(1, N):
    low_1, high_1 = Seg_L.query(0, pivot), Seg_R.query(0, pivot)
    low_2, high_2 = Seg_L.query(pivot, N), Seg_R.query(pivot, N)
    p1 = max(high_1-low_1+1, 0)
    p2 = max(high_2-low_2+1, 0)
    ans = p1+p2
    cand.append(ans)
ans1 = max(cand)

cand2 = []
for rem in range(N):
    rem_low = Seg_L.query(rem, rem+1)
    rem_high = Seg_R.query(rem, rem+1)
    use_low = max(Seg_L.query(0, rem), Seg_L.query(rem+1, N))
    use_high = min(Seg_R.query(0, rem), Seg_R.query(rem+1, N))
    p1 = max(rem_high-rem_low+1, 0)
    p2 = max(use_high-use_low+1, 0)
    ans = p1+p2
    cand2.append(ans)
ans2 = max(cand2)
print(max(ans1, ans2))