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: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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]))

    #1 [lmax, rmin] [*, *]
    #2 [lmax, *] [*, rmin]

    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

    #1
    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))

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

Submission status: Accepted

Solution code:
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]))

    #1 [lmax, rmin] [*, *]
    #2 [lmax, *] [*, rmin]

    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

    #1
    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))

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

Submission status: Accepted

Solution code:
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 # 処理(add or xor max minなど)

    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):
        # [l, r) についてqueryを求める
        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]))

    #1 [lmax, rmin] [*, *]
    #2 [lmax, *] [*, rmin]

    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

    #1
    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))

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

Submission status: Accepted

Solution code:
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 # 処理(add or xor max minなど)

    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):
        # [l, r) についてqueryを求める
        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]))

#1 [lmax, rmin] [*, *]
#2 [lmax, *] [*, rmin]

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

#1
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)

#2
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)

Submission status: Accepted

Solution code:
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()
# print(lr)

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])))
# print(alst)
# print(blst)
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])
# print(lr2)
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]
    # print(tmp,l,r)
    ans=max(ans,tmp+max(0,r-l+1))
print(ans)

Submission status: Accepted

Solution code:
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 

    #min_Rとmax_Lが同じグループにいる時
    max_L = 0
    min_R = INF
    cnt_max = 0 #L最大を満たすのが何個あるか
    cnt_min = 0 #R最小を満たすのが何個あるか
    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)
    
    #min_Rとmax_Lが違うグループにいる時
    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()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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]))
        # lr1[i:]のrの最小値
        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)):
            # lr1[:i]をrmin側にいれる
            _,l,r = lr1[i-1]
            v = max(0, rmin-l+1) + max(0, crmin[i]-lmax+1)
            ans = max(ans, v)
        # すべてrmin or lmax側
        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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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)

#solve
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


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
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

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
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

#Solve
if __name__ == "__main__":
    solve()