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):
n = int(input())
l = 0
r = float("INF")
w = 0
LR = sorted([list(map(int,input().split())) for i in range(n)])
rm = [float("INF")]*(n+1)
for i in range(n):
    rm[-2-i] = min(rm[-1-i],LR[-1-i][1])
for i in range(n):
    x,y = LR[-1-i]
    l = max(l,x)
    r = min(r,y)
    w = max(w,y-x+1)
    rm[-2-i] = min(rm[-1-i],y)
ans = max(r-l+1,0)+w
for k in range(n-1):
    i,j = LR[k]
    a = max(r-i+1,0)
    b = max(rm[k+1]+1-l,0)
    ans = max(ans,a+b)
print(ans)

Solution (Python):
n = int(input())
l = 0
r = float("INF")
w = 0
LR = sorted([list(map(int,input().split())) for i in range(n)])
rm = [float("INF")]*(n+1)
for i in range(n):
    rm[-2-i] = min(rm[-1-i],LR[-1-i][1])
for i in range(n):
    x,y = LR[-1-i]
    l = max(l,x)
    r = min(r,y)
    w = max(w,y-x+1)
    rm[-2-i] = min(rm[-1-i],y)
ans = max(r-l+1,0)+w
for k in range(n-1):
    i,j = LR[k]
    a = max(r-i+1,0)
    b = max(rm[k+1]+1-l,0)
    ans = max(ans,a+b)
print(ans)

Solution (Python):
n = int(input())
l = 0
r = float("INF")
LR = [list(map(int,input().split())) for i in range(n)]
w = 0
for i,j in LR:
    l = max(l,i)
    r = min(r,j)
    w = max(w,j-i+1)
ans = max(r-l+1,0)+w
LR.sort()
rm = [float("INF")]*(n+1)
for i in range(n):
    rm[-2-i] = min(rm[-1-i],LR[-1-i][1])
for k in range(n-1):
    i,j = LR[k]
    a = max(r-i+1,0)
    b = max(rm[k+1]+1-l,0)
    ans = max(ans,a+b)
print(ans)

Solution (Python):
import heapq

n = int(input())
ll, rr = [], []
task = []
ans = 0
for _ in range(n):
    l, r = map(int, input().split())
    heapq.heappush(ll, -l)
    heapq.heappush(rr, r)
    task.append([l, r])
maxl1, minr1 = -heapq.heappop(ll), heapq.heappop(rr)
maxl2, minr2 = -heapq.heappop(ll), heapq.heappop(rr)
for i in range(n):
    ma = maxl1 if not task[i][0] == maxl1 else maxl2
    mi = minr1 if not task[i][1] == minr1 else minr2
    ans = max(ans, task[i][1] - task[i][0] + max(0, mi - ma + 1) + 1)
task.sort()
score = [0] * (n - 1)
l1, r1 = task[0][0], task[0][1]
l2, r2 = task[n - 1][0], task[n - 1][1]
i, j = 0, n - 1
for _ in range(n - 1):
    l1, r1 = max(l1, task[i][0]), min(r1, task[i][1])
    l2, r2 = max(l2, task[j][0]), min(r2, task[j][1])
    j -= 1
    score[i] += max(0, r1 - l1 + 1)
    score[j] += max(0, r2 - l2 + 1)
    i += 1
ans = max(ans, max(score))
print(ans)

Solution (Python):
import heapq

n = int(input())
ll, rr = [], []
task = []
ans = 0
for _ in range(n):
    l, r = map(int, input().split())
    heapq.heappush(ll, -l)
    heapq.heappush(rr, r)
    task.append([l, r])
maxl1, minr1 = -heapq.heappop(ll), heapq.heappop(rr)
maxl2, minr2 = -heapq.heappop(ll), heapq.heappop(rr)
for i in range(n):
    ma = maxl1 if not task[i][0] == maxl1 else maxl2
    mi = minr1 if not task[i][1] == minr1 else minr2
    ans = max(ans, task[i][1] - task[i][0] + max(0, mi - ma + 1) + 1)
for k in range(1):
    task.sort(key = lambda x : x[k])
    score = [0] * (n - 1)
    l1, r1 = task[0][0], task[0][1]
    l2, r2 = task[n - 1][0], task[n - 1][1]
    i, j = 0, n - 1
    for _ in range(n - 1):
        l1, r1 = max(l1, task[i][0]), min(r1, task[i][1])
        l2, r2 = max(l2, task[j][0]), min(r2, task[j][1])
        j -= 1
        score[i] += max(0, r1 - l1 + 1)
        score[j] += max(0, r2 - l2 + 1)
        i += 1
ans = max(ans, max(score))
print(ans)

Solution (Python):
import heapq

n = int(input())
ll, rr = [], []
task = []
ans = 0
for _ in range(n):
    l, r = map(int, input().split())
    heapq.heappush(ll, -l)
    heapq.heappush(rr, r)
    task.append([l, r])
maxl1, minr1 = -heapq.heappop(ll), heapq.heappop(rr)
maxl2, minr2 = -heapq.heappop(ll), heapq.heappop(rr)
for i in range(n):
    ma = maxl1 if not task[i][0] == maxl1 else maxl2
    mi = minr1 if not task[i][1] == minr1 else minr2
    ans = max(ans, task[i][1] - task[i][0] + max(0, mi - ma + 1) + 1)
for k in range(2):
    task.sort(key = lambda x : x[k])
    score = [0] * (n - 1)
    l1, r1 = task[0][0], task[0][1]
    l2, r2 = task[n - 1][0], task[n - 1][1]
    i, j = 0, n - 1
    for _ in range(n - 1):
        l1, r1 = max(l1, task[i][0]), min(r1, task[i][1])
        l2, r2 = max(l2, task[j][0]), min(r2, task[j][1])
        j -= 1
        score[i] += max(0, r1 - l1 + 1)
        score[j] += max(0, r2 - l2 + 1)
        i += 1
ans = max(ans, max(score))
print(ans)

Solution (Python):
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 l==L:
    l=LL[-2]
  if r==-R:
    r=RR[1]
  d=(-R-L+1)+max(0,r-l+1)
  ans=max(ans,d)
print(ans)

Solution (Python):
'''
自宅用PCでの解答
'''
import math

import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 10**18

def main():
    n = int(ipt())
    base = 10**9
    qs = []
    
    lma = 0
    li = -1
    ll = 0
    rmi = INF
    ri = INF
    lr = 0
    mal = 0
    for i in range(n):
        l,r = map(int,ipt().split())
        qs.append((l,r))
        d = r-l+1
        f = True
        if l > lma:
            if ll > mal:
                mal = ll
            lma = l
            li = i
            ll = d
            f = False
        elif l == lma and ll > d:
            li = i
            mal = max(mal,ll)
            ll = d
            f = False
        if r < rmi:
            if lr > mal:
                mal = lr
            rmi = r
            ri = i
            lr = d
            f = False
        elif r == rmi and lr > d:
            ri = i
            mal = max(mal,lr)
            lr = d
            f = False
        if f and mal < d:
            mal = d
    ans = mal+max(0,rmi-lma+1)

    
    q = []
    for la,ra in qs:
        v = (base-1-max(0,ra-lma+1))*base+max(0,rmi-la+1)
        q.append(v)
    q.sort()
    dp0 = [INF,0]
    dp1 = [0,INF]
    f = False
    for i in q:
        l = base-1-i//base
        r = i%base
        if f:
            dp1[1] = min(dp1[1],r)
            if dp0[0]+r > sum(dp1):
                dp1[0] = dp0[0]
                dp1[1] = r
        f = True
        dp0[0] = min(dp0[0],l)

    
    print(max(ans,sum(dp1)))
    
    return None

if __name__ == '__main__':
    main()

Solution (Python):
'''
自宅用PCでの解答
'''
import math

import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 10**18

def main():
    n = int(ipt())
    base = 10**9
    qs = []
    lma = 0
    li = -1
    ll = 0
    rmi = INF
    ri = INF
    lr = 0
    mal = 0
    for i in range(n):
        l,r = map(int,ipt().split())
        qs.append((l,r))
        d = r-l+1
        f = True
        if l > lma:
            if ll > mal:
                mal = ll
            lma = l
            li = i
            ll = d
            f = False
        elif l == lma and ll > d:
            li = i
            mal = max(mal,ll)
            ll = d
            f = False
        if r < rmi:
            if lr > mal:
                mal = lr
            rmi = r
            ri = i
            lr = d
            f = False
        elif r == rmi and lr > d:
            ri = i
            mal = max(mal,lr)
            lr = d
            f = False
        if f and mal < d:
            mal = d

    ans = mal+max(0,rmi-lma+1)


    q = []
    for la,ra in qs:
        v = (base-1-max(0,ra-lma+1))*base+max(0,rmi-la+1)
        q.append(v)

    q.sort()
    dp0 = [INF,0]
    dp1 = [0,INF]
    f = False
    for i in q:
        l = base-1-i//base
        r = i%base
        if f:
            dp1[1] = min(dp1[1],r)
            if dp0[0]+r > sum(dp1):
                dp1[0] = dp0[0]
                dp1[1] = r
        f = True
        dp0[0] = min(dp0[0],l)


    print(max(ans,sum(dp1)))






    return None

if __name__ == '__main__':
    main()

Solution (Python):
n=int(input())
lr=[list(map(int,input().split())) for _ in range(n)]
lr.sort(key=lambda x:x[0])

r0=0
tmpr=float('inf')

l0=0
tmpl=0
for i,x in enumerate(lr):
  l,r=x
  if tmpl<l:
    l0=i
    tmpl=l
  if tmpr>r:
    r0=i
    tmpr=r
if l0==r0:
  ans=lr[r0][1]-lr[l0][0]+1
  tmp=0
  for i in range(n):
    if i==l0:continue
    l,r=lr[i]
    tmp=max(tmp,r-l+1)
  ans+=tmp
  print(ans)
  exit()
ans0=max(0,lr[r0][1]-lr[l0][0]+1)
tmp=0
for i in range(n):
  if i==l0 or i==r0:continue
  l,r=lr[i]
  tmp=max(tmp,r-l+1)
ans0+=tmp


import heapq
class pqheap:
  def __init__(self,key=None):
    self.p = list()
    self.q = list()
  def insert(self,x):
    heapq.heappush(self.p, x)
    return
  def erase(self,x):
    heapq.heappush(self.q, x)
    return
  def minimum(self):
    while self.q and self.p[0] == self.q[0]:
      heapq.heappop(self.p)
      heapq.heappop(self.q)
    return self.p[0] if len(self.p)>0 else None
pq=pqheap()

[pq.insert(x[1]) for i,x in enumerate(lr) if i!=l0 and i!=r0]
l1,r1=lr[r0]
l2,r2=lr[l0]
if pq.minimum():r2=min(r2,pq.minimum())
ans1=max(r1-l1+1,0)
ans1+=max(r2-l2+1,0)
for i,[l,r] in enumerate(lr):
  if i==l0 or i==r0:continue
  tmp=0
  l1=max(l1,l)
  pq.erase(r)
  tmp=max(r1-l1+1,0)
  if pq.minimum():
    r2=min(lr[l0][1],pq.minimum())
  else:
    l2,r2=lr[l0]
  tmp+=max(r2-l2+1,0)
  ans1=max(ans1,tmp)
print(max(ans1,ans0))

Solution (Python):
from operator import itemgetter

class SegTree:  
    """
    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)
        
        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):  
        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):  
        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)

LR.sort(key=lambda item: item[1] - item[0], reverse=True)
lmax = max(l for l, _ in LR[1:])
rmin = min(r for _, r in LR[1:])
ans = max(ans, LR[0][1] - LR[0][0] + 1 + max(rmin - lmax + 1, 0))
print(ans)

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

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

N = int(input())
LR = [tuple(map(int, input().split())) for _ in range(N)]
p = max(Li for Li, _ in LR)
q = min(Ri for _, Ri in LR)
ab = []

for L, R in LR:
    a = max(0, R-p+1)
    b = max(0, q-L+1)
    ab.append((a, b))

ab.sort(key=lambda t: (t[0], -t[1]))
b_min = 10**18
ans = max(0, q-p+1)+max(R-L+1 for L, R in LR)

for i in range(1, N):
    a_min = ab[i][0]
    b_min = min(b_min, ab[i-1][1])
    ans = max(ans, a_min+b_min)

print(ans)

Solution (Python):
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):  
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  
        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):  
        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):  
        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):  
        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 = [lr for lr in LR if lr not in [(minr, lminr), (maxl, rmaxl)]]
LR = [(minr, lminr)] + LR2 + [(maxl, rmaxl)]
M = len(LR)
if M == 1:
    ans = 2 * (LR[0][1] - LR[0][0])
elif M == 2:
    ans = sum(r - l for l, r in LR)
else:
    
    ans = max(0, minr - maxl) + max(r - l for l, r in LR2)
    
    st = SegmentTree([r for l, r in LR], min, 10**10)
    for i in range(1, M):
        v1 = max(0, minr - max(lminr, LR[i - 1][0]))
        v2 = max(0, st.query(i, M) - maxl)
        ans = max(ans, v1 + v2)
print(ans)

Solution (Python):
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):  
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  
        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):  
        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):  
        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):  
        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 = [lr for lr in LR if lr not in [(minr, lminr), (maxl, rmaxl)]]
LR = [(minr, lminr)] + LR2 + [(maxl, rmaxl)]
M = len(LR)
if M == 1:
    ans = 2 * (LR[0][1] - LR[0][0])
elif M == 2:
    ans = sum(r - l for l, r in LR)
else:
    
    ans = max(0, minr - maxl) + max(r - l for l, r in LR2)
    
    st = SegmentTree([r for l, r in LR], min, 10**10)
    for i in range(1, M):
        v1 = max(0, minr - max(lminr, LR[i - 1][0]))
        v2 = max(0, st.query(i, M) - maxl)
        ans = max(ans, v1 + v2)
print(ans)

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



R1 = min(map(lambda t: t[1], LRs))
L2 = max(map(lambda t: t[0], LRs))
LRs.sort(key=lambda t: (-t[0], t[1])) 

ans = 0
R2 = 1001001001
for i in range(1, N):
    R2 = min(R2, LRs[i-1][1])
    L1 = LRs[i][0]  
    ans = max(ans, max(0, R2 - L2 + 1) + max(0, R1 - L1 + 1))



LRs.sort(key = lambda t: t[0] - t[1])
one_problem_contest = LRs[0][1] - LRs[0][0] + 1
L_max = max(map(lambda t: t[0], LRs[1:]))
R_min = min(map(lambda t: t[1], LRs[1:]))
ans = max(ans, one_problem_contest + max(R_min - L_max + 1, 0))

print(ans)

Solution (Python):
INF = 10 ** 10

N = int(input())
 
L = [tuple(map(int,input().split())) for _ in range(N)]
 
L.sort(key=lambda x:(-x[0], x[1]))
 
MAX_L = 0
MIN_R = INF
MAX = 0
a = 0
b = 0
 
for i in range(N):
    if MAX_L < L[i][0]:
        MAX_L = L[i][0]
        a = i
    if MIN_R > L[i][1]:
        MIN_R = L[i][1]
        b = i
    MAX = max(MAX, L[i][1] - L[i][0] + 1)
 
ans = MAX + max(0, MIN_R - MAX_L + 1)
 
p = INF
 
for i in range(N-1):
    p = min(p, L[i][1])
    ans = max(ans, max(0, p - L[a][0] + 1) + max(0, L[b][1] - L[i+1][0] + 1))
 
print(ans)

Solution (Python):
N = int(input())
X = sorted([list(map(int, input().split())) for _ in range(N)], key=lambda x: (x[0], -x[1]))


front = []
most_left_R = float('inf')
for l, r in X:
    most_left_R = min(r, most_left_R)
    front.append(max(0, most_left_R - l + 1))

back = []
most_left_R = float('inf')
for l, r in X[::-1]:
    most_left_R = min(r, most_left_R)
    back.append(max(0, most_left_R - X[-1][0] + 1))
back = back[::-1]

ans = 0
for i in range(N - 1):
    ans = max(ans, front[i] + back[i + 1])

most_left_R = min([r for l, r in X])
for l, r in X:
    ans = max(ans, (r - l + 1) + max(0, most_left_R - X[-1][0] + 1))
print(ans)

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


front = []
most_left_R = float('inf')
for l, r in X:
    most_left_R = min(r, most_left_R)
    front.append(max(0, most_left_R - l + 1))

back = []
most_left_R = float('inf')
for l, r in X[::-1]:
    most_left_R = min(r, most_left_R)
    back.append(max(0, most_left_R - X[-1][0] + 1))
back = back[::-1]

ans = 0
for i in range(N - 1):
    ans = max(ans, front[i] + back[i + 1])

most_left_R = min([r for l, r in X])
for l, r in X:
    ans = max(ans, (r - l + 1) + max(0, most_left_R - X[-1][0] + 1))
print(ans)

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


def solve():
    N = int(input())
    l = [tuple(map(int, input().split())) for i in range(N)]
    l.sort(key=lambda x:(x[0], -x[1]))

    
    

    lmax = 0
    rmin = 10**12
    a, b = 0, 0

    for i in range(N):
        if lmax < l[i][0]:
            lmax = l[i][0]
            a = i
        if rmin > l[i][1]:
            rmin = l[i][1]
            b = i

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

    
    ans2 = 0
    p = 10**18
    for i in range(1, N)[::-1]:
        p = min(p, l[i][1])
        ans2 = max(ans2, max(l[b][1]-l[i-1][0]+1, 0)+max(p-l[a][0]+1, 0))

    ans = max(ans1, ans2)
    print(ans)


if __name__ == "__main__":
    solve()

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


def solve():
    N = int(input())
    l = [tuple(map(int, input().split())) for i in range(N)]
    l.sort(key=lambda x:(x[0], -x[1]))

    
    

    lmax = 0
    rmin = 10**12
    a, b = 0, 0

    for i in range(N):
        if lmax < l[i][0]:
            lmax = l[i][0]
            a = i
        if rmin > l[i][1]:
            rmin = l[i][1]
            b = i

    
    ans1 = 0
    for i in range(N):
        if i==a or i==b:
            continue
        ans1 = max(ans1, max(l[b][1]-l[a][0]+1, 0)+max(l[i][1]-l[i][0]+1, 0))

    
    ans2 = 0
    p = 10**18
    for i in range(1, N)[::-1]:
        p = min(p, l[i][1])
        ans2 = max(ans2, max(l[b][1]-l[i-1][0]+1, 0)+max(p-l[a][0]+1, 0))

    ans = max(ans1, ans2)
    print(ans)


if __name__ == "__main__":
    solve()

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


class SegTree():
    def __init__(self, N, e, operator_func):
        self.e = e 
        self.size = N
        self.node = [self.e] * (2*N)
        self.operator_func = operator_func 

    def set_list(self, l):
        for i in range(self.size):
            self.node[i+self.size-1] = l[i]
        for i in range(self.size-1)[::-1]:
            self.node[i] = self.operator_func(self.node[2*i+1], self.node[2*i+2])
    
    def update(self, k, x):
        k += self.size-1
        self.node[k] = x
        while k >= 0:
            k = (k - 1) // 2
            self.node[k] = self.operator_func(self.node[2*k+1], self.node[2*k+2])

    def get(self, l, r):
        
        x = self.e
        l += self.size
        r += self.size

        while l<r:
            if l&1:
                x = self.operator_func(x, self.node[l-1])
                l += 1
            if r&1:
                r -= 1
                x = self.operator_func(x, self.node[r-1])
            l >>= 1
            r >>= 1
        return x


def solve():
    N = int(input())
    l = [tuple(map(int, input().split())) for i in range(N)]
    l.sort(key=lambda x:(x[0], -x[1]))

    
    

    lmax = 0
    rmin = 10**12
    a, b = 0, 0

    for i in range(N):
        if lmax < l[i][0]:
            lmax = l[i][0]
            a = i
        if rmin > l[i][1]:
            rmin = l[i][1]
            b = i

    
    ans1 = 0
    for i in range(N):
        if i==a or i==b:
            continue
        ans1 = max(ans1, max(l[b][1]-l[a][0]+1, 0)+max(l[i][1]-l[i][0]+1, 0))

    
    ans2 = 0
    tree = SegTree(N, 10**12, min)
    tree.set_list([i[1] for i in l])
    for i in range(N-1):
        ans2 = max(ans2, max(l[b][1]-l[i][0]+1, 0)+max(tree.get(i+1, N)-l[a][0]+1, 0))

    ans = max(ans1, ans2)
    print(ans)


if __name__ == "__main__":
    solve()

Solution (Python):
from itertools import product
from operator import add


class SegTree():
    def __init__(self, N, e, operator_func=add):
        self.e = e 
        self.size = N
        self.node = [self.e] * (2*N)
        self.operator_func = operator_func 

    def set_list(self, l):
        for i in range(self.size):
            self.node[i+self.size-1] = l[i]
        for i in range(self.size-1)[::-1]:
            self.node[i] = self.operator_func(self.node[2*i+1], self.node[2*i+2])
    
    def update(self, k, x):
        k += self.size-1
        self.node[k] = x
        while k >= 0:
            k = (k - 1) // 2
            self.node[k] = self.operator_func(self.node[2*k+1], self.node[2*k+2])

    def get(self, l, r):
        
        x = self.e
        l += self.size
        r += self.size

        while l<r:
            if l&1:
                x = self.operator_func(x, self.node[l-1])
                l += 1
            if r&1:
                r -= 1
                x = self.operator_func(x, self.node[r-1])
            l >>= 1
            r >>= 1
        return x


N = int(input())
l = [tuple(map(int, input().split())) for i in range(N)]
l.sort(key=lambda x:(x[0], -x[1]))




lmax = 0
rmin = 10**12
a, b = 0, 0

for i in range(N):
    if lmax < l[i][0]:
        lmax = l[i][0]
        a = i
    if rmin > l[i][1]:
        rmin = l[i][1]
        b = i


ans1 = 0
for i in range(N):
    if i==a or i==b:
        continue
    buf = max(l[b][1]-l[a][0]+1, 0)+max(l[i][1]-l[i][0]+1, 0)
    ans1 = max(ans1, buf)


ans2 = 0
tree = SegTree(N, 10**12, min)
tree.set_list([i[1] for i in l])

for i in range(N-1):
    p1 = l[i][0]
    p2 = tree.get(i+1, N)
    buf = max(l[b][1]-p1+1, 0)+max(p2-l[a][0]+1, 0)
    ans2 = max(ans2, buf)

ans = max(ans1, ans2)
print(ans)

Solution (Python):
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
lr=[list(map(int,input().split())) for i in range(n)]
lr.sort()


alst=[(lr[0][0],lr[0][1])]
blst=[(lr[-1][0],lr[-1][1])]
for i in range(n-1):
    alst.append((lr[i+1][0], min(alst[i][1],lr[i+1][1])))
    blst.append((max(blst[i][0],lr[-i-2][0]), min(blst[i][1],lr[-i-2][1])))


ans=0
def sa(lst):
    return max(0,lst[1]-lst[0]+1)

for i in range(n-1):
    ans=max(ans,sa(alst[i])+sa(blst[-i-2]))

lr2=sorted(lr,key=lambda x: x[1])

for i in range(n):
    tmp=sa(lr[i])
    l,r=0,0
    if lr[i][0]==lr[-1][0]:
        l=lr[-2][0]
    else:
        l=lr[-1][0]
    if lr[i][1]==lr2[0][1]:
        r=lr2[1][1]
    else:
        r=lr2[0][1]
    
    ans=max(ans,tmp+max(0,r-l+1))
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def main():
    N = int(input())
    prob = [tuple(map(int,input().split())) for _ in range(N)]
    
    if N == 2:
        ans = sum(r - l + 1 for l,r in prob)
        print(ans)
        return 

    
    max_L = 0
    min_R = INF
    cnt_max = 0 
    cnt_min = 0 
    for l,r in prob:
        if l == max_L:
            cnt_max += 1
        elif l > max_L:
            cnt_max = 1
            max_L = l
        if r == min_R:
            cnt_min += 1
        elif r < min_R:
            cnt_min = 1
            min_R = r
    
    if cnt_min > 1 and cnt_max > 1:
        max_diff = max(r - l for l,r in prob) + 1
    elif cnt_min > 1:
        max_diff = max(r - l for l,r in prob if l != max_L) + 1
    elif cnt_max > 1:
        max_diff = max(r - l for l,r in prob if r != min_R) + 1
    else:
        max_diff = max(r - l for l,r in prob if (r != min_R) and (l != max_L)) + 1
    
    ans1 = max_diff + max(min_R - max_L + 1,0)
    
    
    prob.sort(key = lambda x:(x[1],x[0]))
    cummax_L = prob[0][0]
    ans2 = 0
    for l,r in prob[1:]:
        ans2 = max(ans2,max(r - max_L + 1,0) + max(min_R - cummax_L + 1,0))
        cummax_L = max(cummax_L,l)

    print(max(ans1,ans2))
if __name__ == '__main__':
    main()