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 math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n = I()
    lr = sorted([LI() for _ in range(n)])
    la = [x[0] for x in lr]
    ra = sorted([x[1] for x in lr])

    rr = 0
    for l, r in lr:
        t = r - l + 1
        tl = la[-1]
        if l == tl:
            tl = la[-2]
        tr = ra[0]
        if r == tr:
            tr = ra[1]
        if tr >= tl:
            t += tr - tl + 1
        if rr < t:
            rr = t

    mr = [lr[0][1]]
    for _, r in lr[1:]:
        if mr[-1] > r:
            mr.append(r)
        else:
            mr.append(mr[-1])

    tl, tr = lr[-1]
    for i in range(n-2, 0, -1):
        r = lr[i][1]
        if tr > r:
            tr = r
        if tr < tl:
            break
        if mr[i-1] < lr[i-1][0]:
            continue
        t = tr - tl + 1 + mr[i-1] - lr[i-1][0] + 1
        if rr < t:
            rr = t

    return rr

print(main())

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")

n = int(input())
lr = [None]*n
for i in range(n):
    l,r = map(int, input().split())
    lr[i] = (i,l,r)

lr1 = sorted(lr, key=lambda x: x[1])
lr2 = sorted(lr, key=lambda x: x[2])
lmax = lr1[-1][1]
rmin = lr2[0][2]
lmaxi, rmini = lr1[-1][0], lr2[0][0]
if lr1[-1][0]==lr2[0][0]:
    ans = max(0, rmin-lmax+1) + max(r-l+1 for i,l,r in lr1 if i!=lr1[-1][0])
else:
    ans = max(0, rmin-lmax+1) + max(r-l+1 for i,l,r in lr1)
    
    lr1 = [(i,l,r) for i,l,r in lr1 if i not in (lmaxi, rmini)]
    lr2 = [(i,l,r) for i,l,r in lr2 if i not in (lmaxi, rmini)]
    if len(lr1)==0:
        ans = max(ans, (lr[0][2]-lr[0][1]+1) + (lr[1][2]-lr[1][1]+1))
    else:
        lr1.sort(key=lambda x: (x[1], -x[2]))
        
        crmin = [0]*len(lr1)
        crmin[-1] = lr1[-1][2]
        for i in range(len(lr1)-2, -1, -1):
            crmin[i] = min(crmin[i+1], lr1[i][2])
        
        for i in range(1,len(lr1)):
            
            _,l,r = lr1[i-1]
            v = max(0, rmin-l+1) + max(0, crmin[i]-lmax+1)
            ans = max(ans, v)
        
        v = max(0, rmin-lr1[-1][1]+1) + max(0, lr[lmaxi][2]-lr[lmaxi][1]+1)
        ans = max(ans, v)

        v = max(0, rmin-lr[rmini][1]+1) + max(0, crmin[0] - lmax +1)
        ans = max(ans, v)
print(ans)

Solution (Python):
n = int(input())
lr = [tuple(map(int, input().split())) for _ in range(n)]
ans = max(r - l + 1 for l, r in lr)
lr.sort()
ml, mr = lr.pop()
lr.sort(key=lambda x: x[1])
l2, r2 = lr[0]
if n >= 3 and ml <= r2:
    ans = max(ans, min(mr, r2) - ml + 1 + max(ri - li + 1 for li, ri in lr[1:]))
for l, r in lr[1:]:
    if ml <= r:
        ans = max(ans, min(mr, r) - ml + 1 + r2 - l2 + 1)
    l2, r2 = max(l2, l), min(r2, r)
    if not l2 <= r2:
        break
else:
    ans = max(ans, mr - ml + 1 + r2 - l2 + 1)
print(ans)

Solution (Python):
import sys

input=sys.stdin.readline

N=int(input())
p=[]
for i in range(N):
    p.append(tuple(map(int,input().split())))

p.sort()

rmin=[0]*N
rmin[0]=p[0][1]
for i in range(1,N):
    rmin[i]=min(rmin[i-1],p[i][1])

kukan=[(0,0)]*N
kukan[-1]=p[-1]
for i in range(N-2,-1,-1):
    l1,r1=p[i]
    l2,r2=kukan[i+1]
    kukan[i]=(max(l1,l2),min(r1,r2))

l1,r1=p[0]
l2,r2=kukan[1]
ans=max(0,r1-l1+1)+max(0,r2-l2+1)

for i in range(1,N-1):
    l1,r1=p[i]
    l2,r2=kukan[i+1]
    R=rmin[i-1]
    test1=max(0,r1-l1+1)+max(0,min(r2,R)-l2+1)
    test2=max(0,r2-l2+1)+max(0,min(r1,R)-l1+1)
    ans=max(ans,test1,test2)

print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline
from itertools import accumulate
n=int(input())
LR=[list(map(int,input().split())) for _ in range(n)]
ans=max(r-l+1 for l,r in LR)+max(0,min(r for l,r in LR)-max(l for l,r in LR)+1)
LR.sort()
R_min=list(accumulate([r for l,r in LR],min))
R_min_r=list(accumulate([r for l,r in LR[::-1]],min))[::-1]
_ans=0
for i in range(n-1):
	_ans=max(_ans,max(0,R_min[i]-LR[i][0]+1)+max(0,R_min_r[i+1]-LR[-1][0]+1))
print(max(ans,_ans))

Solution (Python):
import sys
from itertools import accumulate
N,*L = map(int, open(0).read().split())
ls = []
ml = -1
nr = -1
li = -1
mr = 10**9
nl = -1
ri = -1
for i,(a,b) in enumerate(zip(*[iter(L)]*2)):
  ls.append((a,b))
  if ml<a:
    ml = a
    nr = b
    li = i
  if b<mr:
    mr = b
    nl = a
    ri = i

if ri!=li:
  a,b = min(li,ri),max(li,ri)
  ls.pop(b)
  ls.pop(a)
  N -= 2
else:
  ls.pop(li)
  N -= 1
if N==0:
  ans = max(mr-nl+1,0)+max(nr-ml+1,0)
  print(ans)
  sys.exit()
ls.sort()
length = max(c[1]-c[0]+1 for c in ls)
ans = max(mr-ml+1,0)+length
r = list(accumulate((c[1] for c in ls[::-1]), min))[::-1]
l = list(c[0] for c in ls)
ans = max(ans, max(mr-nl+1,0)+max(r[0]-ml+1,0))
for i in range(N-1):
  xl = max(nl,l[i])
  xr = min(nr,r[i+1])
  ans = max(ans, max(mr-xl+1,0)+max(xr-ml+1,0))
xl = max(nl,l[N-1])
ans = max(ans, max(mr-xl+1,0)+nr-ml+1)
print(ans)

Solution (Python):
import sys
from itertools import accumulate
N,*L = map(int, open(0).read().split())
ls = [0]*N
ml = -1
nr = -1
li = -1
mr = 10**9
nl = -1
ri = -1
for i,(a,b) in enumerate(zip(*[iter(L)]*2)):
  ls[i] = a,b
  if ml<a:
    ml = a
    nr = b
    li = i
  if b<mr:
    mr = b
    nl = a
    ri = i

if ri!=li:
  a,b = min(li,ri),max(li,ri)
  ls.pop(b)
  ls.pop(a)
  N -= 2
else:
  ls.pop(li)
  N -= 1
if N==0:
  ans = max(mr-nl+1,0)+max(nr-ml+1,0)
  print(ans)
  sys.exit()
ls.sort()
length = max(c[1]-c[0]+1 for c in ls)
ans = max(mr-ml+1,0)+length
r = list(accumulate((c[1] for c in ls[::-1]), min))[::-1]
l = list(c[0] for c in ls)
ans = max(ans, max(mr-nl+1,0)+max(r[0]-ml+1,0))
for i in range(N-1):
  xl = max(nl,l[i])
  xr = min(nr,r[i+1])
  ans = max(ans, max(mr-xl+1,0)+max(xr-ml+1,0))
xl = max(nl,l[N-1])
ans = max(ans, max(mr-xl+1,0)+nr-ml+1)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
lmx = 0
lmxi = -1
rmn = 10**18
rmni = -1
ansls = []
anstmp = 0
a.sort(reverse=True)
for i in range(n):
  if a[i][0] >= lmx:
    lmx = a[i][0]
    lmxi = i
  if rmn >= a[i][1]:
    rmn = a[i][1]
    rmni = i
for i in range(n):
  if i not in (lmxi,rmni):
    anstmp = max(anstmp,a[i][1]-a[i][0]+1)
ansls.append(anstmp+max(0,rmn-lmx+1))
rmnt = a[0][1]
rmnls = [0 for i in range(n)]
rmnls[-1] = a[-1][1]
for i in range(n-1)[::-1]:
  rmnls[i] = min(rmnls[i+1],a[i][1])
for i in range(n-1):
  rmnt = min(rmnt,a[i][1])
  anstmp = 0
  anstmp += max(0,rmn-a[i+1][0]+1)
  anstmp += max(0,rmnt-lmx+1)
  ansls.append(anstmp)
print(max(ansls))

Solution (Python):
n = int(input())
h = [tuple(map(int, input().split())) for i in range(n)]
L = [x[0] for x in h]
R = [x[1] for x in h]

lmax = max(L)
lidx = L.index(lmax)
rmin = min(R)
ridx = R.index(rmin)

ret = max(0, 1 + rmin - lmax) + max(0, 1 + max(r - l for l, r in h))

g = [[max(0, 1 + r - lmax), max(0, 1 + rmin - l)] for l, r in h]
g.sort(key=lambda x: (x[0], -x[1]))
A = [x[0] for x in g]
B = [x[1] for x in g]
minb = 10**9
for i in range(n-1):
    if minb > B[i]:
        minb = B[i]
    if ret < minb + A[i+1]:
        ret = minb + A[i+1]
print(ret)

Solution (Python):
n = int(input())
L,R = [0]*n,[0]*n
for i in range(n):
    L[i],R[i] = map(int,input().split())
    R[i] += 1

M = L.index(max(L))
m = R.index(min(R))

d = [R[i] - L[i] if M != i != m else 0 for i in range(n)]
ans = max(d) + max(R[m] - L[M], 0)
d[m] = R[m] - L[m]
d[M] = R[M] - L[M]
if m == M:
    print(ans)
    exit()
if n == 2:
    print(d[m] + d[M])
    exit()
a,b = [0]*(n-2),[0]*(n-2)
j = 0
for i in range(n):
    if m != i != M:
        a[j],b[j] = max(R[i]-L[M],0) , max(R[m]-L[i],0)
        j += 1
ab = sorted(list(zip(a,b)),reverse = True)
mb = [0]*len(a)
for i in range(len(a))[::-1]:
    if i == len(a)-1:
        mb[i] = ab[i][1]
    else:
        mb[i] = min(ab[i][1], mb[i+1])
for i in range(len(a) - 1):
    ans = max(ans,min(ab[i][0],d[M]) + min(mb[i + 1],d[m]))
ans = max(ans , d[M] + min(mb[0], d[m]), min(ab[len(a)-1][0],d[M]) + d[m])

print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10

class SlidingWindowAggregation:
    """ https://scrapbox.io/data-structures/Sliding_Window_Aggregation """
    
    def __init__(self, f=sum):
        self.f = f
        self.front_stack = deque()
        self.back_stack = deque()
    
    def empty(self):
        return self.front_stack or self.back_stack

    def __len__(self):
        return len(self.front_stack) + len(self.back_stack)

    def fold_all(self):
        try:
            assert self.empty(), "Both stack is empty"
            if not self.front_stack:
                return self.back_stack[-1][1]
            elif not self.back_stack:
                return self.front_stack[-1][1]
            else:
                return self.f(self.front_stack[-1][1], self.back_stack[-1][1])
        except AssertionError as err:
            print("AssertionError :", err)

    def push(self, x):
        if not self.back_stack:
            self.back_stack.append((x, x))
        else:
            tmp = self.f(self.back_stack[-1][1], x)
            self.back_stack.append((x, tmp))

    def popleft(self):
        try:
            assert self.empty(), "Both stack is empty"
            if not self.front_stack:
                x,fx = self.back_stack.pop()
                self.front_stack.append((x, x))
                while self.back_stack:
                    x, fx = self.back_stack.pop()
                    fx = self.f(x, self.front_stack[-1][1])
                    self.front_stack.append((x, fx))
            self.front_stack.pop()

        except AssertionError as err:
            print("AssertionError :", err)


def solve():
    n = II()
    lr = LIR(n)
    maxl = max([l for l, r in lr])
    minr = min([r for l, r in lr])
    ans = max(minr - maxl + 1, 0) + max([r - l + 1 for l, r in lr])
    lisminr = SlidingWindowAggregation(min)
    lr.sort()
    for _, r in lr:
        lisminr.push(r)

    for l, r in lr[:-1]:
        lisminr.popleft()
        ans = max(ans, max(minr - l + 1, 0) + max(lisminr.fold_all() - maxl + 1, 0))
    print(ans)
    return



if __name__ == '__main__':
    solve()

Solution (Python):
def kazu(p, q):
    return max(p[0], q[0]), min(p[1], q[1]), max(-max(p[0], q[0]) + min(p[1], q[1]) + 1, 0)
def kazu1(p):
    return max(p[1] - p[0] + 1, 0)
def main():
    N = int(input())
    l = []
    for _ in range(N):
        L, R = map(int, input().split())
        l.append((L, R))
    l.sort(key=lambda x:x[1])
    dp= (l[0], l[1])
    for i in range(2, N):
        a, b, c = kazu(dp[0], l[i]) 
        d, e, f = kazu(dp[1], l[i])
        g, h, j = kazu(dp[0], dp[1])
        m = max(f + kazu1(dp[0]), c + kazu1(dp[1]), j + kazu1(l[i]))
        if  m == f + kazu1(dp[0]):
            dp = ((d,e),dp[0])
        elif m == c + kazu1(dp[1]):
            dp = ((a,b),dp[1])
        else:
            dp = ((g,h), l[i])
    return kazu1(dp[0]) + kazu1(dp[1])
print(main())

Solution (Python):
def main():
    N = int(input())
    LR = [tuple(map(int, input().split())) for _ in range(N)]
    LR.sort(key=lambda x: x[1])
    l1, r1 = LR[0]
    l2, r2 = LR[1]
    def ss(a, b, c, d):
        l, r = max(a, c), min(b, d)
        return r - l + 1 if l <= r else 0

    for l, r in LR[2:]:
        t1 = ss(l1, r1, l, r) + (r2 - l2)
        t2 = ss(l2, r2, l, r) + (r1 - l1)
        t3 = ss(l1, r1, l2, r2) + (r - l)
        if t3 == max(t1, t2, t3):
            l1, r1 = max(l1, l2), min(r1, r2)
            if l1 > r1:
                l1 = r1 + 1
            l2, r2 = l, r
        elif t1 > t2:
            l1, r1 = max(l1, l), min(r1, r)
            if l1 > r1:
                l1 = r1 + 1
        else:
            l2, r2 = max(l2, l), min(r2, r)
            if l2 > r2:
                l2 = r2 + 1
    return r1 - l1 + r2 - l2 + 2


print(main())

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

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

A.sort()

Il = []
L = 1
R = 10**9

for i in range(N):
    l, r = A[i]
    L = max(L, l)
    R = min(R, r)
    Il.append(max(0, R - L + 1))

Ir = []
L = 1
R = 10**9

for i in range(N)[::-1]:
    l, r = A[i]
    L = max(L, l)
    R = min(R, r)
    Ir.append(max(0, R - L + 1))

Ir = Ir[::-1]
res = 0

for i in range(N - 1):
    res = max(res, Il[i] + Ir[i + 1])

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

maxrange = A[-1][1] - A[-1][0] + 1

L = 1
R = 10**9

for i in range(N - 1):
    l, r = A[i]
    L = max(L, l)
    R = min(R, r)

res = max(res, maxrange + max(0,R - L + 1))

print(res)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

class SlidingWindowAggretgation:
    def __init__(self, default, f = min):
        self.default = default
        self.f = f
        self.front_stack = deque()
        self.back_stack = deque()

    def get(self):
        res = self.default
        if self.front_stack:
            res = self.f(res, self.front_stack[-1][1])
        if self.back_stack:
            res = self.f(res, self.back_stack[-1][1])
        return res

    def append(self, x):
        fx = x
        if self.back_stack:
            fx = self.f(self.back_stack[-1][1], x)
        self.back_stack.append((x, fx))

    def popleft(self):
        if not self.front_stack:
            x, fx = self.back_stack.pop()
            self.front_stack.append((x, x))
            while self.back_stack:
                x, fx = self.back_stack.pop()
                fx = self.f(x, self.front_stack[-1][1])
                self.front_stack.append((x, fx))
        self.front_stack.pop()

def solve():
    n = I()
    p = LIR(n)
    p.sort()
    maxl = max([l for (l,r) in p])
    minr = min([r for (l,r) in p])
    ans = max(0, minr-maxl+1)+max([r-l+1 for (l,r) in p])
    swagll = SlidingWindowAggretgation(0,max)
    swagrr = SlidingWindowAggretgation(float("inf"),min)
    for l,r in p:
        swagrr.append(r)
    for l,r in p[:-1]:
        swagll.append(l)
        swagrr.popleft()
        ll = swagll.get()
        rr = swagrr.get()
        k = max(minr-ll+1,0)+max(rr-maxl+1,0)
        if ans < k:
            ans = k
    print(ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

class SlidingWindowAggretgation:
    def __init__(self, default, f = min):
        self.default = default
        self.f = f
        self.front_stack = deque()
        self.back_stack = deque()

    def get(self):
        res = self.default
        if self.front_stack:
            res = self.f(res, self.front_stack[-1][1])
        if self.back_stack:
            res = self.f(res, self.back_stack[-1][1])
        return res

    def append(self, x):
        fx = x
        if self.back_stack:
            fx = self.f(self.back_stack[-1][1], x)
        self.back_stack.append((x, fx))

    def popleft(self):
        if not self.front_stack:
            x, fx = self.back_stack.pop()
            self.front_stack.append((x, x))
            while self.back_stack:
                x, fx = self.back_stack.pop()
                fx = self.f(x, self.front_stack[-1][1])
                self.front_stack.append((x, fx))
        self.front_stack.pop()

def solve():
    n = I()
    p = LIR(n)
    p.sort()
    maxl = max([l for (l,r) in p])
    minr = min([r for (l,r) in p])
    ans = max(0, minr-maxl+1)+max([r-l+1 for (l,r) in p])
    swagll = SlidingWindowAggretgation(0,max)
    swaglr = SlidingWindowAggretgation(float("inf"),min)
    swagrl = SlidingWindowAggretgation(0,max)
    swagrr = SlidingWindowAggretgation(float("inf"),min)
    for l,r in p:
        swagrl.append(l)
        swagrr.append(r)
    for l,r in p[:-1]:
        swagll.append(l)
        swaglr.append(r)
        swagrl.popleft()
        swagrr.popleft()
        ll = swagll.get()
        lr = swaglr.get()
        rl = swagrl.get()
        rr = swagrr.get()
        k = max(lr-ll+1,0)+max(rr-rl+1,0)
        if ans < k:
            ans = k
    print(ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
lr = [LI() + [i] for i in range(n)]
x = sorted(lr, reverse=1)
L_max,R_,idx1 = x[0]
x = sorted(lr, key = itemgetter(1))
L_, R_min,idx2 = x[0]
tmp = 0
for l,r,i in lr:
    if i == idx1 or i == idx2:
        continue
    tmp = max(tmp,r-l+1)
ans1 = max(0,R_min - L_max+1) + tmp
lst = [[max(0,r-L_max+1),l,i] for l,r,i in lr]
lst.sort()
tmp1 = inf
ans2 = 0
for i in range(1,n):
    tmp1 = min(tmp1, max(0,R_min - lst[i-1][1]+1))
    tmp2 = lst[i][0]
    ans2 = max(ans2,tmp1+tmp2)
print(max(ans1,ans2))

Solution (Python):
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True 
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
lr = []
lmrer = BIG  
lmrel = BIG
rmlel = -BIG 
rmler = -BIG
mx1 = -BIG
for i in range(n):
    l,r = inm()
    lr.append((l,r))
    
    if r < lmrer or r==lmrer and l<lmrel:
        lmrer = r
        lmrel = l
        lmrei = i
    
    if l > rmlel or l==rmlel and r>rmlel:
        rmlel = l
        rmler = r
        rmlei = i
    if r-l>mx1:
        mx1 = r-l

if n==2:
    print(lr[0][1]-lr[0][0]+1 + lr[1][1]-lr[1][0]+1)
    exit()


mx = max(0,lmrer-rmlel+1)+mx1+1
if lmrei==rmlei:
    print(mx)
    exit()

i1 = max(lmrei,rmlei)
i2 = min(lmrei,rmlei)
del lr[i1]
del lr[i2]
lr.sort()

rminr = [0]*(n-2)
rminr[n-3] = lr[n-3][1]
for i in range(n-4,-1,-1):
    rminr[i] = min(rminr[i+1],lr[i][1])


len1 = lmrer-lmrel+1
len2 = rminr[0]-rmlel+1
mx = max(mx, len1+len2)

for i in range(n-3):
    len1 = lmrer-max(lmrel,lr[i][0])+1
    len2 = min(rmler,rminr[i+1])-rmlel+1
    mx = max(mx,len1+len2)


len1 = lmrer-max(lmrel,lr[n-3][0])+1
len2 = rmler-rmlel+1
mx = max(mx,len1+len2)

print(mx)

Solution (Python):
N = int(input())
LR = [[0, 0] for i in range(N)]
p = q = -1
Lp = 0
Rq = 10**9 + 1
w_max = 0
for i in range(N):
  L, R = map(int, input().split())
  if L > Lp:
    Lp = L
    p = i
  if R < Rq:
    Rq = R
    q = i
  w_max = max(w_max, R-L+1)
  LR[i] = [L, R]



ans = w_max + max(Rq-Lp+1, 0)
if p == q:
  print(ans)
  quit()


ab = []
wp = LR[p][1] - Lp + 1
wq = Rq - LR[q][0] + 1
for i in range(N):
  if i==p or i==q:
    continue
  ab.append([
    min(wp, max(LR[i][1]-Lp+1, 0)), -min(wq, max(Rq-LR[i][0]+1, 0))
  ])


ab.sort()
ab.append([wp, 0])
b_min = wq
for a, b in ab:
  ans = max(ans, a+b_min)
  b_min = min(b_min, -b)

print(ans)

Solution (Python):
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
maxl = 1
minr = 10**9+1
maxdis = 0
for i in range(N):
    if maxl < LR[i][0]:
        maxl = LR[i][0]
    if minr > LR[i][1]:
        minr = LR[i][1]
    if LR[i][1] - LR[i][0] > maxdis:
        maxdis = LR[i][1] - LR[i][0]

res = maxdis+1 + max(0, minr - maxl+1)

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

minb = 10**9+5
for i in range(N-1, -1, -1):
    minb = min(minb, max(0, LR[i][1]-maxl+1))
    LR[i].append(minb)
for i in range(N-1):
    res = max(res, max(0, minr - LR[i][0]+1)+LR[i+1][2])
print(res)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
a = [list(map(int, input().split())) for _ in range(N)]
for i in range(N): a[i][1] += 1
a.sort()
ls = [x[0] for x in a]
rs = [x[1] for x in a]

class SegTree:
  def segfunc(self, x, y):
    return min(x, y) 
  def __init__(self, n, ide_ele, init_val):
    
    self.ide_ele = ide_ele
    
    self.num = 2 ** (n - 1).bit_length()
    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
class Seg2ree:
  def segfunc(self, x, y):
    return max(x, y) 
  def __init__(self, n, ide_ele, init_val):
    
    self.ide_ele = ide_ele
    
    self.num = 2 ** (n - 1).bit_length()
    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
res = 0
segls = Seg2ree(N, 0, ls)
segrs = SegTree(N, 10 ** 10, rs)

for i in range(N - 1):
  l1 = segls.query(0, i)
  l2 = segls.query(i + 1, N)
  r1 = segrs.query(0, i)
  r2 = segrs.query(i + 1, N)
  if l1 == 0: l1 = 10 ** 10
  if r1 > 10 ** 9: r1 = a[i][1]
  t = a[i][1] - a[i][0] + max(0, min(r1, r2) - l2)
  t = max(t, max(0, r1 - a[i][0]) + r2 - l2)
  
  res = max(res, t)
print(res)

Solution (Python):
from bisect import *
from collections import *
from fractions import gcd
from math import factorial
from itertools import *
from heapq import *



N=int(input())
LR=[list(map(int,input().split())) for i in range(N)]
for i in range(N):
    LR[i][1]+=1

value=max([R-L for L,R in LR])

LR=sorted(LR,key=lambda x:x[0]*10**9+x[1])
a=2*(10**9)
minRlst=[a for i in range(N)]
minRlst[-1]=LR[-1][1]
maxLlst=[0 for i in range(N)]
maxLlst[0]=LR[0][0]
for i in range(N-2,-1,-1):
    minRlst[i]=min(minRlst[i+1],LR[i][1])
for i in range(1,N):
    maxLlst[i]=max(minRlst[i-1],LR[i][0])
L1,R1=LR[0]
L2,R2=LR[-1][0],minRlst[1]
maxR=min([R for L,R in LR])
for i in range(0,N-1):
    L,R=LR[i]
    a=max(R-L,0)
    b=max(maxR-LR[-1][0],0)
    value=max(value,a+b)
    L1=L
    R1=min(R1,R)
    R2=minRlst[i+1]
    a=max(R1-L1,0)
    b=max(R2-L2,0)
    value=max(value,a+b)
print(value)

Solution (Python):
from itertools import accumulate
from operator import add
N = int(input())
LR = [tuple(map(int, input().split())) for _ in range(N)]
LR.sort()
f = lambda lr1, lr2: (max(lr1[0], lr2[0]), min(lr1[1], lr2[1]))
g = lambda lr: max(0, lr[1]-lr[0]+1)
A = list(map(g, accumulate(LR, f)))
B = list(map(g, accumulate(LR[::-1], f)))[-2::-1]
res = max(max(map(g, LR)) + A[-1], max(map(add, A, B)))
print(res)

Solution (Python):
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))



N = I()
L,R = Line(N,2)

l = max(L)
li = L.index(l)
r = min(R)
ri = R.index(r)
ans = max(r-l+1,0) + max([0 if (i==li or i==ri) else R[i]-L[i]+1 for i in range(N)])
if li==ri:
    print(ans)
    exit()

x = []
for i in range(N):
    if i==li or i==ri:
        continue
    else:
        x1 = max(R[i]-l+1, 0)
        x2 = max(r-L[i]+1, 0)
        x.append((x1,x2))

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

amin = R[li]-l+1
bmin = r-L[ri]+1
one = [amin]
two = [bmin]

for x0 in x:
    amin = min(amin,x0[0])
    one.append(amin)
for x0 in x[::-1]:
    bmin = min(bmin,x0[1])
    two.append(bmin)

two = list(reversed(two))
for i in range(len(one)):
    temp = one[i]+two[i]
    if temp>ans:
        ans = temp

print(ans)

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

maxLR = 10**9

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

LRs.sort()

accMinRs = [LRs[0][1]]
for L, R in LRs[1:]:
    accMinRs.append(min(accMinRs[-1], R))

accMinRRevs = [LRs[-1][1]]
for L, R in reversed(LRs[:-1]):
    accMinRRevs.append(min(accMinRRevs[-1], R))
accMinRRevs.reverse()

L2 = LRs[-1][0]
ans = 0
for x in range(N-1):
    L1, R1 = LRs[x]
    L0 = LRs[x-1][0] if x > 0 else 0
    R0 = accMinRs[x] if x > 0 else maxLR
    R2 = accMinRRevs[x+1]
    score1 = max(0, min(R0, R1)-max(L0, L1)+1) + max(0, R2-L2+1)
    score2 = max(0, R1-L1+1) + max(0, min(R0, R2)-max(L0, L2)+1)
    ans = max(ans, score1, score2)

print(ans)