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:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, LR):
    LR.sort(key=lambda x: x[1])
    LR.sort(key=lambda x: x[0])


    lc = []
    l = 0
    r = INF
    for i in range(N):
        l_, r_ = LR[i]
        l = max(l, l_)
        r = min(r, r_)
        lc.append((l, r))
    
    rc = []
    l = 0
    r = INF
    for i in range(N-1, -1, -1):
        l_, r_ = LR[i]
        l = max(l, l_)
        r = min(r, r_)
        rc.append((l, r))
    
    def c(l, r):
        return max(0, r-l+1)

    ans = 0
    for i in range(N-1):
        ans = max(ans, c(*lc[i]) + c(*rc[N-1-1-i]))
    for i in range(N):
        tmp = c(*LR[i])
        l, r = (0, INF)
        if i != 0:
            l = max(l, lc[i-1][0])
            r = min(r, lc[i-1][1])
        if i != N-1:
            l = max(l, rc[N-1-i][0])
            r = min(r, rc[N-1-i][1])
            
        tmp += c(l, r)
        ans = max(ans, tmp)

    return ans


def main():
    N = read_int()
    LR = [read_int_n() for _ in range(N)]
    print(slv(N, LR))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from operator import itemgetter
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
for i in range(n):
  l[i]=[l[i][0],l[i][1],(l[i][0]+l[i][1])/2]
len=[]
for i in range(n):
  len.append(l[i][1]-l[i][0]+1)
maxlen=max(len)
x=len.index(maxlen)
L3=1;R3=10**9
for i in range(n):
  if l!=x:
    L3=max(L3,l[i][0])
    R3=min(R3,l[i][1])
c=maxlen+max(R3-L3+1,0)

l=sorted(l,key=itemgetter(2))
L=[]
R=[]
for i in range(n):
  L.append(l[i][0])
for i in range(n):
  R.append(l[i][1])
L1=1;R1=10**9
L2=1;R2=10**9
list=[]
list2=[]
for i in range(n-1):
  L1=max(L1,l[i][0])
  R1=min(R1,l[i][1])
  list.append(max(R1-L1+1,0))
for i in range(n-1,0,-1):
  L2=max(L2,l[i][0])
  R2=min(R2,l[i][1])
  list2.append(max(R2-L2+1,0))

list2.reverse()
ans=[]
for i in range(n-1):
  ans.append(list[i]+list2[i])
a=max(ans)
print(max(a,c))

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate


def calc(tasks):
    tasks_l, tasks_r = zip(*tasks)
    tasks_l_acc_fwd = list(accumulate(tasks_l, func=max))
    tasks_l_acc_bwd = list(reversed(list(accumulate(reversed(tasks_l), func=max))))
    tasks_r_acc_fwd = list(accumulate(tasks_r, func=min))
    tasks_r_acc_bwd = list(reversed(list(accumulate(reversed(tasks_r), func=min))))
    # print(tasks)
    # print(tasks_r_acc_fwd)
    # print(tasks_r_acc_bwd)

    score = 0
    for i in range(1, n):
        left_max_l = tasks_l_acc_fwd[i - 1]
        left_min_r = tasks_r_acc_fwd[i - 1]
        right_max_l = tasks_l_acc_bwd[i]
        right_min_r = tasks_r_acc_bwd[i]
        tmp_score = max(0, left_min_r - left_max_l + 1) + max(0, right_min_r - right_max_l + 1)
        score = max(score, tmp_score)
    return score


n = int(input())
appeared_lr = set()
tasks = []
for line in sys.stdin:
    l, r = list(map(int, line.split()))
    appeared_lr.add(l)
    appeared_lr.add(r)
    tasks.append((l, r))

tasks.sort()
ans1 = calc(tasks)

tasks.sort(key=lambda lr: (lr[0], -lr[1]))
ans2 = calc(tasks)

tasks.sort(key=lambda lr: (lr[1] - lr[0], lr[0], lr[1]))
ans3 = calc(tasks)

print(max(ans1, ans2, ans3))

Submission status: Accepted

Solution code:

def sc(l,r):
    return max(0,r-l+1)

N = int(input())

al1 = 0
al2 = 0
ar1 = 0
ar2 = 0
nmax = 0

LR = []
for i in range(N):
    nL,nR = map(int,input().split())
    LR.append([nL,nR])

LR.sort()

for i in range(N):

    L = LR[i][0]
    R = LR[i][1]

    if i == 0:
        al1 = L
        ar1 = R

    elif i == 1:
        al2 = L
        ar2 = R

    else:

        nmax = 0
        nmax = max(nmax, sc(max(al1,al2),min(ar1,ar2)) + sc(L,R) )
        nmax = max(nmax, sc(max(al1,L),min(ar1,R)) + sc(al2,ar2) )
        nmax = max(nmax, sc(max(al2,L),min(ar2,R)) + sc(al1,ar1) )
        #print (nmax)

        if nmax == (sc(max(al1,al2),min(ar1,ar2)) + sc(L,R)):

            nal1 = max(al1,al2)
            nar1 = min(ar1,ar2)
            nal2 = L
            nar2 = R
            #print ("a")

        elif nmax == (sc(max(al1,L),min(ar1,R)) + sc(al2,ar2) ):

            nal1 = max(al1,L)
            nar1 = min(ar1,R)
            nal2 = al2
            nar2 = ar2
            #print ("b")

        else:

            nal1 = max(al2,L)
            nar1 = min(ar2,R)
            nal2 = al1
            nar2 = ar1
            #print ("c")

        al1 = nal1
        al2 = nal2
        ar1 = nar1
        ar2 = nar2

    #print (al1,ar1,al2,ar2)

print (sc(al1,ar1) + sc(al2,ar2))

Submission status: Accepted

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

def honya(LR):
  l = LR[-1][0]
  r = LR[-1][1]
  D = [0] * N
  for i in range(N - 1, -1, -1):
    l = max(l, LR[i][0])
    r = min(r, LR[i][1])
    D[i] = max(0, r - l + 1)

  l = LR[0][0]
  r = LR[0][1]
  ans = 0
  for i in range(N - 1):
    r = min(r, LR[i][1])
    ans = max(ans, max(r - l + 1, 0) + D[i + 1])

  return ans

LR.sort(reverse = True)
#for i in range(N):
#  print(LR[i], LR[i][1] - LR[i][0])
  
ans = honya(LR)

R = 0
for i in range(N):
  R = max(R, LR[i][1])
for i in range(N):
  LR[i][0], LR[i][1] = R - LR[i][1], R - LR[i][0]
  
LR.sort(reverse = True)
ans = max(ans, honya(LR))

def honyamorake(LR):
  ans = 0
  x = 0
  for i in range(N):
    t = LR[i][1] - LR[i][0] + 1
    if t > ans:
      ans = t
      x = i
  return ans + honyapun(LR, x)

def honyapun(LR, x):
  l = 0
  r = 10 ** 10
  for i in range(N):
    if i != x:
      l = max(l, LR[i][0])
      r = min(r, LR[i][1])
  if l > r:
    return 0
  else:
    return r - l + 1

ans = max(ans, honyamorake(LR))

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
data=[list(map(int,input().split())) for i in range(n)]
data.sort()
l,r=data[0]
lst=[0]*n
lst[0]=r-l+1
for i in range(1,n):
    a,b=data[i]
    l=a
    if b<r:
        r=b
    lst[i]=max(0,r-l+1)
li=[0]*n
l,r=data[n-1]
li[n-1]=r-l+1
for i in range(1,n):
    a,b=data[n-1-i]
    if b<r:
        r=b
    li[n-1-i]=max(0,r-l+1)
k=0
s=0
for i in range(n):
    l,r=data[i]
    if k<=r-l+1:
        k=r-l+1
        s=i
l=0
r=10**9+1
for i in range(n):
    if i==s:
        continue
    a,b=data[i]
    l=max(l,a)
    r=min(r,b)
ans=k+max(0,r-l+1)
for i in range(n-1):
    ans=max(ans,lst[i]+li[i+1])
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

task = []
N = int(input())
for _ in range(N):
    task.append(list(map(int, input().split())))

task.sort()
#print(task)
ans = 0

task_minmax = [None] * (N+1)
task_minmax[N] = [0, 10**9]
for i in range(N-1, -1, -1):
    task_minmax[i] = [max(task_minmax[i+1][0], task[i][0]), min(task_minmax[i+1][1], task[i][1])]

mini = 0
maxi = 10**9

#print(task_minmax)

for i in range(N-1):
    temp = 0
    if i != 0:
        ans = max(ans, max(0, min(maxi, task_minmax[i+1][1]) - max(mini, task_minmax[i+1][0]) + 1) + (task[i][1] - task[i][0]) + 1)

    mini = max(task[i][0], mini)
    maxi = min(task[i][1], maxi)

    temp += max(maxi - mini + 1, 0)
    temp += max(task_minmax[i+1][1] - task_minmax[i+1][0] + 1, 0)

    ans = max(temp, ans)

print(ans)

Submission status: Accepted

Solution code:
from operator import itemgetter
import bisect


def cross(a, b):
    l = max(a[0], b[0])
    r = min(a[1], b[1])
    if l <= r:
        return (l, r)
    else:
        return (-1, -2)
    
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
info = sorted(info, key = itemgetter(1))
max_ans = 0

l_ans = [(0, 10**9)]
for i in range(n):
    tmp = cross(l_ans[-1], info[i])
    l_ans.append(tmp)

r_ans = [(0, 10**9)]
for i in range(n)[::-1]:
    tmp = cross(r_ans[-1], info[i])
    r_ans.append(tmp)
r_ans = r_ans[::-1]

for i in range(1,n):
    ans = (l_ans[i][1] - l_ans[i][0]) + (r_ans[i][1] - r_ans[i][0]) + 2
    max_ans = max(ans, max_ans)
    
for i in range(n):
    ans = info[i][1] - info[i][0] + 1
    tmp = cross(l_ans[i], r_ans[i+1])
    ans += tmp[1] - tmp[0] + 1
    max_ans = max(ans, max_ans)

info = sorted(info)
l_ans = [(0, 10**9)]
for i in range(n):
    tmp = cross(l_ans[-1], info[i])
    l_ans.append(tmp)

r_ans = [(0, 10**9)]
for i in range(n)[::-1]:
    tmp = cross(r_ans[-1], info[i])
    r_ans.append(tmp)
r_ans = r_ans[::-1]

for i in range(1,n):
    ans = (l_ans[i][1] - l_ans[i][0]) + (r_ans[i][1] - r_ans[i][0]) + 2
    max_ans = max(ans, max_ans)
print(max_ans)

Submission status: Accepted

Solution code:
from heapq import heappop, heappush


def solve_b(n, l_list, r_list):

    l_max = max(l_list)
    r_min = min(r_list)

    # l_max and r_min in same contest
    res_1 = max(0, r_min - l_max + 1)
    # one problem contest
    res_1 += max([r_list[i] - l_list[i] + 1 for i in range(n)])

    # l_max in one, r_min in the other
    hr = []
    for i in range(n):
        if r_list[i] > r_min:
            heappush(hr, (r_list[i], i))
    r_need = min([r_list[i] for i in range(n) if l_list[i] == l_max])
    l_temp = max([l_list[i] for i in range(n) if r_list[i] == r_min])

    res_2 = 0
    while len(hr) > 0:
        r, i = heappop(hr)
        res_2 = max(res_2, max(0, min(r, r_need) - l_max + 1) + max(0, r_min - l_temp + 1))
        l_temp = max(l_temp, l_list[i])
    res_2 = max(res_2, max(0, r_need - l_max + 1) + max(0, r_min - l_temp + 1))

    return max(res_1, res_2)


def main():
    n = int(input())
    l_list = [0] * n
    r_list = [0] * n
    for i in range(n):
        l, r = map(int, input().split())
        l_list[i] = l
        r_list[i] = r
    res = solve_b(n, l_list, r_list)
    print(res)


def test():
    assert solve_b(4, [4, 1, 5, 2], [7, 4, 8, 5]) == 6
    assert solve_b(4, [1, 2, 3, 4], [20, 19, 18, 17]) == 34


if __name__ == "__main__":
    test()
    main()

Submission status: Runtime Error

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

Submission status: Runtime Error

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


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

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

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

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

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


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

Submission status: Runtime Error

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


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

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

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

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

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


st = SegmentTree([r for l, r in LR], min, 10**10)
ans = max(
    st.query(0, i) + st.query(i, N) - LR[i - 1][0] - LR[-1][0]
    for i in range(1, N))
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)
ans = max(
    ans, minr - maxl + max(r - l
                           for l, r in LR if (l, r) not in ((maxl, rmaxl),
                                                            (lminr, minr))))
print(ans)

Submission status: Runtime Error

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 = 0

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


    print(ans)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 = 0

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


    print(ans)

Submission status: Runtime Error

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)]
    
    #min_Rとmax_Lが同じグループにいる時
    max_L = 0
    min_R = INF
    cnt_max = 0 #L最大を満たすのが何個あるか
    cnt_min = 0 #R最小を満たすのが何個あるか
    for i,(l,r) in enumerate(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)
    elif cnt_min > 1:
        max_diff = max(r - l for l,r in prob if l != max_L)
    elif cnt_max > 1:
        max_diff = max(r - l for l,r in prob if r != min_R)
    else:
        max_diff = max(r - l for l,r in prob if (r != min_R) and (l != max_L))
    
    ans1 = max_diff + max(min_R - max_L + 1,0) + 1
    
    #min_Rとmax_Lが違うグループにいる時
    prob.sort(key = lambda x:x[1])
    diff = prob[0][1] - prob[0][0]
    cummax_L = prob[0][0]
    for l,r in prob[1:]:
        diff = max(diff,r - cummax_L)
        cummax_L = max(cummax_L,l)
    
    ans2 = min_R - max_L + diff + 2

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

Submission status: Runtime Error

Solution code:
"""
1st 1 2 3 4 | 5 6 7 | 8  
2nd 1 | 2 3 4 | 5 6 7 8
なるべく多くのカブリが生えるようにしたい

⇨まず、なるべく遠くの2つを選ぶのがポイント？
右端の最も小さいやつと、左端の最も大きいやつを選ぶか。

------l------r------
--l--r--------------
↑初見で最もカブリ小さいやつ

右端の小さい順に見て、何個の島に分けられるかを先に出す
1個 : r-1の最大と最小が答え
2個 : それぞれの島のrmin-lmaxが答え
3個以上 : 0
"""

from operator import itemgetter
n = int(input())
ps  = []
for i in range(n):
    l,r = map(int, input().split())
    ps.append((r-l+1,l,r))

# 右端の小さい順
cnt = 0
r_min = -1
l_max = 0
r_max = 0
l_min = 10**10
psr = sorted(ps,key=itemgetter(2))
cnts = []
for n,l,r in psr:
    r_max = max(r,r_max)
    l_min = min(l,l_min)
    # print(l_max, r_min, n,l,r)
    if l > r_min:
        cnt += 1
        # cnts.append(r_min - l_max + 1)
        r_min = r
        l_max = l
    else:
        l_max = max(l_max, l)
    if cnt == 3:
        print(0)
        exit()
# print(cnt,l_min,r_max)
# 島が1つしかなくて、かつ全域を覆う範囲が存在する
ps = sorted(ps,reverse=True)
if cnt == 1 and ps[0][1] == l_min and ps[0][2] == r_max:
    print(ps[0][0] + ps[-1][0])
    exit()



psl = sorted(ps,key=itemgetter(1),reverse = True)
a_range = psl[0]
psr = sorted(psl[1:],key=itemgetter(2))
b_range = psr[0]
ps = sorted(psr[1:], itemgetter(1))

for n, l, r in ps:
    an,al,ar = a_range
    bn,bl,br = b_range
    al2 = max(al,l)
    ar2 = min(ar,r)
    an2 = ar2 - al2 + 1
    bl2 = max(bl,l)
    br2 = min(br,r)
    bn2 = br2 - bl2 + 1
    if an2 <= 0 and bn2 <= 0:
        print(0)
        exit()
    elif an2 > 0 and bn2 <= 0:
        a_range = (an2, al2, ar2)
    elif bn2 > 0 and an2 <= 0:
        b_range = (bn2, bl2, br2)
    else:
        if an2 + bn  < bn2 + an:
            #bを更新
            b_range = (bn2, bl2, br2)
        else:
            a_range = (an2, al2, ar2)

an, _, _ = a_range
bn, _, _ = b_range
print(an+bn)

"""
4
1 2
2 3
4 5
3 4

"""

Submission status: Runtime Error

Solution code:
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
length = 0
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
  length = max(length, b-a+1)

ans = max(mr-ml+1,0)+length
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
ls.sort()
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: Runtime Error

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])
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(a[i],d[M]) + min(mb[i + 1],d[m]))
ans = max(ans , d[M] + min(mb[0], d[m]), min(a[len(a)-1],d[M]) + d[m])

print(ans)

Submission status: Runtime Error

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)
if m == M:
    print(ans)
    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])
d[m] = R[m] - L[m]
d[M] = R[M] - L[M]
for i in range(len(a) - 1):
    ans = max(ans,min(a[i],d[M]) + min(mb[i + 1],d[m]))
ans = max(ans , d[M] + min(mb[0], d[m]), min(a[len(a)-1],d[M]) + d[m])

print(ans)

Submission status: Runtime Error

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 if l != maxl and r != minr])
    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()

Submission status: Runtime Error

Solution code:
N, *L = map(int, open('0').read().split())
inf = []
ls = []
rs = []
fl = 0
fr = float('inf')
for i,x in enumerate(zip(*[iter(L)]*2)):
  l,r = x
  ls.append((l,i))
  rs.append((r,i))
  inf.append((l,r))
ls.sort()
rs.sort(reverse=True)
m = 0
used = [False]*N
l1 = -1
l2 = -2
r1 = -1
r2 = -2
while True:
  while l1>=-N:
    i = ls[l1][1]
    if not used[i]:
      break
    l1 -= 1
  else:
    break
  while r1>=-N:
    i = rs[r1][1]
    if not used[i]:
      break
    r1 -= 1
  else:
    break
  while l2>=-N:
    i = ls[l2][1]
    if (not used[i]) and l1>l2:
      break
    l2 -= 1
  else:
    break
  while r2>=-N:
    i = rs[r2][1]
    if (not used[i]) and r1>r2:
      break
    r2 -= 1
  else:
    break
  x = rs[r1][0]-ls[l1][0]+1
  fa = m+x
  
  ll, i = ls[l1]
  rr, j= rs[r1]
  if i==j:
    lr = inf[i][1]
    a,b = max(ll,fl),min(lr,fr)
    p,q = a,b
    lm = b-a+1
    lx = rs[r1][0]-ls[l2][0]+1
    la = lm+lx
    rm = lm
    ra = la
  else:
    lr = inf[i][1]
    a = max(ll,fl)
    b = min(lr,fr)
    lm = b-a+1
    lx = rs[r1][0]-ls[l2][0]+1
    la = lm+lx
  
    rl = inf[j][0]
    p = max(rl,fl)
    q = min(rr,fr)
    rm = q-p+1
    rx = rs[r2][0]-ls[l1][0]+1
    ra = rm+rx
  if la>ra:
    if la>fa:
      fl = a
      fr = b
      m = lm
      used[i] = True
    else:
      break
  else:
    if ra>fa:
      fl = p
      fr = q
      m = rm
      used[j] = True
    else:
      break
first = [0,float('inf')]
second = [0,float('inf')]
for i,flag in enumerate(used):
  if flag:
    first[0] = max(first[0], inf[i][0])
    first[1] = min(first[1], inf[i][1])
  else:
    second[0] = max(second[0], inf[i][0])
    second[1] = min(second[1], inf[i][1])
if float('inf') in first or float('inf') in second:
  print(0)
else:
  ans = first[1]-first[0]+1 + second[1]-second[0]+1
  print(max(0,ans))