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: Wrong Answer

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:


from operator import itemgetter


# In[2]:


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


# In[5]:


ans = 0


# In[6]:


def func(list):
    ret = []
    left = list[0][0]
    right = list[0][1]
    ret.append(right - left + 1)
    for i in range(1, len(list)):
        left = max(left, list[i][0])
        right = min(right, list[i][1])
        ret.append(right - left + 1)
    return ret


# In[7]:


LR.sort(key=itemgetter(1))
LR.sort(key=itemgetter(0))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[8]:


m = 0
for i in range(N - 1):
    m = max(m, list1[i] + list2[N - i - 2])
ans = max(ans, m)


# In[ ]:


LR.sort(key=itemgetter(1), reverse=True)
LR.sort(key=itemgetter(0))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[ ]:


m = 0
for i in range(N - 1):
    m = max(m, list1[i] + list2[N - i - 2])
ans = max(ans, m)


# In[9]:


LR.sort(key=itemgetter(1))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[10]:


m = 0
for i in range(N - 1):
    m = max(m, list1[i] + list2[N - i - 2])
ans = max(ans, m)


# In[11]:


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


# In[12]:


print(ans)


# In[ ]:

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:


from operator import itemgetter


# In[2]:


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


# In[3]:


# LR.sort()


# In[4]:


# LR


# In[5]:


def func(list):
    ret = []
    left = list[0][0]
    right = list[0][1]
    ret.append(right - left + 1)
    for i in range(1, len(list)):
        left = max(left, list[i][0])
        right = min(right, list[i][1])
        ret.append(right - left + 1)
    return ret


# In[6]:


LR.sort(key=itemgetter(0))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[7]:


m1 = 0
for i in range(N - 1):
    m1 = max(m1, list1[i] + list2[N - i - 2])
# m1


# In[8]:


LR.sort(key=itemgetter(1))
list1 = func(LR)
LR.reverse()
list2 = func(LR)
m2 = 0
for i in range(N - 1):
    m2 = max(m2, list1[i] + list2[N - i - 2])
# m2


# In[9]:


m3 = 0
for i in range(N):
    m3 = max(m3, LR[i][1] - LR[i][0] + 1)
# m3


# In[10]:


print(max(m1, m2, m3))


# In[ ]:

Submission status: Wrong Answer

Solution code:
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 query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        res = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                res = f(res, dat[l])
                l += 1
            if r & 1:
                r -= 1
                res = f(dat[r], res)
            l >>= 1
            r >>= 1
        return res


I = [int(_) for _ in open(0).read().split()]
N = I[0]
LR = sorted(zip(I[1::2], I[2::2]), key=lambda lr: lr[0] * 10**10 - lr[1])
L = [l for l, r in LR]
R = [r for l, r in LR]
STR = SegmentTree(R, min, 10**9 + 1)
ans = 0
for i in range(N - 1):
    ans = max([
        ans,
        max(0,
            STR.query(0, i + 1) - L[i]) + max(0,
                                              STR.query(i + 1, N) - L[-1]) + 2
    ])
print(ans)

Submission status: Wrong Answer

Solution code:
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 query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        res = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                res = f(res, dat[l])
                l += 1
            if r & 1:
                r -= 1
                res = f(dat[r], res)
            l >>= 1
            r >>= 1
        return res


I = [int(_) for _ in open(0).read().split()]
N = I[0]
LR = sorted(zip(I[1::2], I[2::2]))
L = [l for l, r in LR]
R = [r for l, r in LR]
STR = SegmentTree(R, min, 10**9 + 1)
ans = 0
for i in range(N - 1):
    ans = max([
        ans,
        max(0,
            STR.query(0, i + 1) - L[i]) + max(0,
                                              STR.query(i + 1, N) - L[-1]) + 2
    ])
'''
RL = sorted(zip(I[2::2], I[1::2]))[::-1]
R = [r for r, l in RL]
L = [l for r, l in RL]
STL = SegmentTree(L, max, 0)
for i in range(N - 1):
    ans = max([
        ans,
        max(0, R[i] - STL.query(0, i + 1)) +
        max(0, R[-1] - STL.query(i + 1, N)) + 2
    ])
'''
print(ans)

Submission status: Wrong Answer

Solution code:
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 query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        res = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                res = f(res, dat[l])
                l += 1
            if r & 1:
                r -= 1
                res = f(dat[r], res)
            l >>= 1
            r >>= 1
        return res


I = [int(_) for _ in open(0).read().split()]
N = I[0]
LR = sorted(zip(I[1::2], I[2::2]))
L = [l for l, r in LR]
R = [r for l, r in LR]
STR = SegmentTree(R, min, 10**9 + 1)
ans = 0
for i in range(N - 1):
    ans = max([
        ans,
        max(0,
            STR.query(0, i + 1) - L[i]) + max(0,
                                              STR.query(i + 1, N) - L[-1]) + 2
    ])
RL = sorted(zip(I[2::2], I[1::2]))[::-1]
R = [r for r, l in RL]
L = [l for r, l in RL]
STL = SegmentTree(L, max, 0)
for i in range(N - 1):
    ans = max([
        ans,
        max(0, R[i] - STL.query(0, i + 1)) +
        max(0, R[-1] - STL.query(i + 1, N)) + 2
    ])
print(ans)

Submission status: Wrong Answer

Solution code:
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 query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        res = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                res = f(res, dat[l])
                l += 1
            if r & 1:
                r -= 1
                res = f(dat[r], res)
            l >>= 1
            r >>= 1
        return res


I = [int(_) for _ in open(0).read().split()]
N = I[0]
LR = sorted(zip(I[1::2], I[2::2]))
L = [l for l, r in LR]
R = [r for l, r in LR]
STR = SegmentTree(R, min, 10**9 + 1)
ans = 0
for i in range(N - 1):
    ans = max([
        ans,
        max(0,
            STR.query(0, i + 1) - L[i]) + max(0,
                                              STR.query(i + 1, N) - L[-1]) + 2
    ])
RL = sorted(zip(I[2::2], I[1::2]))[::-1]
R = [r for r, l in RL]
L = [l for r, l in RL]
STL = SegmentTree(L, max, 0)
for i in range(N - 1):
    ans = max([
        ans,
        max(0, R[i] - STL.query(0, i + 1)) +
        max(0, R[-1] - STR.query(i + 1, N)) + 2
    ])
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True



## Segment Tree ##

## Initializer Template ##
# Range Sum:        sg=SegTree(n,0)
# Range Minimum:    sg=SegTree(n,inf,min,inf)

class SegTree:

    def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
        self.n=n
        self.ide_ele=ide_ele=ide
        self.num=num=2**(n-1).bit_length()
        self.seg=seg=[self.ide_ele]*2*self.num
        self.segfun=segfun=function
        #set_val
        for i in range(n):
            self.seg[i+self.num-1]=init_val
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfun(self.seg[2*i+1],self.seg[2*i+2]) 
    
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfun(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfun(res,self.seg[p])
            if q&1 == 1:
                res = self.segfun(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfun(res,self.seg[p])
        else:
            res = self.segfun(self.segfun(res,self.seg[p]),self.seg[q])
        return res

    def __str__(self):
        # 生配列を表示
        rt=self.seg[self.num-1:self.num-1+self.n]
        return str(rt)


ans=0

n=I()
c=[]
for i in range(n):
    l,r=LI()
    c.append((l,r))

c.sort(key=lambda x:(x[0],-x[1]))
sg=SegTree(n,inf,min,inf)

for i in range(n):
    sg.update(i,c[i][1])

ln=c[-1][0]
for k in range(0,n-1):
    l,r=c[k]
    alt=max(sg.query(0,k+1)-l+1,0) + max(sg.query(k+1,n)-ln+1,0)
    ans=max(alt,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True



## Segment Tree ##

## Initializer Template ##
# Range Sum:        sg=SegTree(n,0)
# Range Minimum:    sg=SegTree(n,inf,min,inf)

class SegTree:

    def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
        self.n=n
        self.ide_ele=ide_ele=ide
        self.num=num=2**(n-1).bit_length()
        self.seg=seg=[self.ide_ele]*2*self.num
        self.segfun=segfun=function
        #set_val
        for i in range(n):
            self.seg[i+self.num-1]=init_val
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfun(self.seg[2*i+1],self.seg[2*i+2]) 
    
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfun(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfun(res,self.seg[p])
            if q&1 == 1:
                res = self.segfun(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfun(res,self.seg[p])
        else:
            res = self.segfun(self.segfun(res,self.seg[p]),self.seg[q])
        return res

    def __str__(self):
        # 生配列を表示
        rt=self.seg[self.num-1:self.num-1+self.n]
        return str(rt)


ans=0

n=I()
c=[]
for i in range(n):
    l,r=LI()
    c.append((l,r))

c.sort()
sg=SegTree(n,inf,min,inf)

for i in range(n):
    sg.update(i,c[i][1])
ln=c[-1][0]
for k in range(0,n-1):
    l,r=c[k]
    alt=max(sg.query(0,k+1)-l+1,0) + max(sg.query(k+1,n)-ln+1,0)
    ans=max(alt,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True



## Segment Tree ##

## Initializer Template ##
# Range Sum:        sg=SegTree(n,0)
# Range Minimum:    sg=SegTree(n,inf,min,inf)

class SegTree:

    def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
        self.n=n
        self.ide_ele=ide_ele=ide
        self.num=num=2**(n-1).bit_length()
        self.seg=seg=[self.ide_ele]*2*self.num
        self.segfun=segfun=function
        #set_val
        for i in range(n):
            self.seg[i+self.num-1]=init_val
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfun(self.seg[2*i+1],self.seg[2*i+2]) 
    
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfun(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfun(res,self.seg[p])
            if q&1 == 1:
                res = self.segfun(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfun(res,self.seg[p])
        else:
            res = self.segfun(self.segfun(res,self.seg[p]),self.seg[q])
        return res

    def __str__(self):
        # 生配列を表示
        rt=self.seg[self.num-1:self.num-1+self.n]
        return str(rt)


ans=0

n=I()
c=[]
for i in range(n):
    l,r=LI()
    c.append((l,r))

c.sort()
sg=SegTree(n,inf,min,inf)

for i in range(n):
    sg.update(i,c[i][1])

ln=c[-1][0]
for k in range(0,n-1):
    l,r=c[k]
    alt=max(sg.query(0,k+1)-l+1,0) + max(sg.query(k+1,n+1)-ln+1,0)
    if alt!=inf:ans=max(alt,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True



## Segment Tree ##

## Initializer Template ##
# Range Sum:        sg=SegTree(n,0)
# Range Minimum:    sg=SegTree(n,inf,min,inf)

class SegTree:

    def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
        self.n=n
        self.ide_ele=ide_ele=ide
        self.num=num=2**(n-1).bit_length()
        self.seg=seg=[self.ide_ele]*2*self.num
        self.segfun=segfun=function
        #set_val
        for i in range(n):
            self.seg[i+self.num-1]=init_val
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfun(self.seg[2*i+1],self.seg[2*i+2]) 
    
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfun(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfun(res,self.seg[p])
            if q&1 == 1:
                res = self.segfun(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfun(res,self.seg[p])
        else:
            res = self.segfun(self.segfun(res,self.seg[p]),self.seg[q])
        return res

    def __str__(self):
        # 生配列を表示
        rt=self.seg[self.num-1:self.num-1+self.n]
        return str(rt)


ans=0

n=I()
c=[]
for i in range(n):
    l,r=LI()
    c.append((l,r))

c.sort()
sg=SegTree(n,inf,min,inf)

for i in range(n):
    sg.update(i,c[i][1])

ln=c[-1][0]
for k in range(0,n-1):
    l,r=c[k]
    alt=max(sg.query(0,k+1)-l+1,0) + max(sg.query(k+1,n+1)-ln+1,0)
    if alt==inf:ans=max(alt,ans)
   

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True



## Segment Tree ##

## Initializer Template ##
# Range Sum:        sg=SegTree(n,0)
# Range Minimum:    sg=SegTree(n,inf,min,inf)

class SegTree:

    def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
        self.n=n
        self.ide_ele=ide_ele=ide
        self.num=num=2**(n-1).bit_length()
        self.seg=seg=[self.ide_ele]*2*self.num
        self.segfun=segfun=function
        #set_val
        for i in range(n):
            self.seg[i+self.num-1]=init_val
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfun(self.seg[2*i+1],self.seg[2*i+2]) 
    
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfun(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfun(res,self.seg[p])
            if q&1 == 1:
                res = self.segfun(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfun(res,self.seg[p])
        else:
            res = self.segfun(self.segfun(res,self.seg[p]),self.seg[q])
        return res

    def __str__(self):
        # 生配列を表示
        rt=self.seg[self.num-1:self.num-1+self.n]
        return str(rt)


ans=0

n=I()
c=[]
for i in range(n):
    l,r=LI()
    c.append((l,r))

c.sort()
sg=SegTree(n,inf,min,inf)

for i in range(n):
    sg.update(i,c[i][1])

ln=c[-1][0]
for k in range(0,n-1):
    l,r=c[k]
    alt=max(sg.query(0,k+1)-l+1,0) + max(sg.query(k+1,n+1)-ln+1,0)
    ans=max(alt,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
#show_flg=True



## Segment Tree ##

## Initializer Template ##
# Range Sum:        sg=SegTree(n,0)
# Range Minimum:    sg=SegTree(n,inf,min,inf)

class SegTree:

    def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
        self.n=n
        self.ide_ele=ide_ele=ide
        self.num=num=2**(n-1).bit_length()
        self.seg=seg=[self.ide_ele]*2*self.num
        self.segfun=segfun=function
        #set_val
        for i in range(n):
            self.seg[i+self.num-1]=init_val
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfun(self.seg[2*i+1],self.seg[2*i+2]) 
    
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfun(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfun(res,self.seg[p])
            if q&1 == 1:
                res = self.segfun(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfun(res,self.seg[p])
        else:
            res = self.segfun(self.segfun(res,self.seg[p]),self.seg[q])
        return res

    def __str__(self):
        # 生配列を表示
        rt=self.seg[self.num-1:self.num-1+self.n]
        return str(rt)


ans=0

n=I()
c=[]
for i in range(n):
    l,r=LI()
    c.append((l,r))

c.sort()
sg=SegTree(n,inf,min,inf)

for i in range(n):
    sg.update(i,c[i][1])
ln=c[-1][0]
for k in range(1,n-1):
    l,r=c[k]
    alt=max(sg.query(0,k+1)-l+1,0) + max(sg.query(k+1,n+1)-ln+1,0)
    ans=max(alt,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import combinations
import numpy as np

def fun(g):
    minimum = np.max(g[:, 0])
    maximum = np.min(g[:, 1])
    return max(0, maximum - minimum + 1)


def bruteforce(lr):
    index = list(range(len(lr)))
    max_fun = 0
    for n in range(1, len(lr)):
        for group1 in combinations(index, n):
            group1 = np.array(group1)
            group2 = np.array([i for i in index if i not in group1])
            funny = fun(lr[group1]) + fun(lr[group2])
            # max_fun = max(max_fun, funny)
            if max_fun <= funny:
                max_fun = funny
                max_group1 = group1
                max_group2 = group2
            else:
                pass
    # print(max_group1, fun(lr[max_group1]))
    # print(max_group2, fun(lr[max_group2]))
    return max_fun

def minmaxsplit(lr):
    argmin = np.argmin(lr, axis=0)
    argmax = np.argmax(lr, axis=0)
    max_min = argmin[1]
    min_max = argmax[0]
    if max_min == min_max:
        return 0
    lefty = lr[max_min]
    righty = lr[min_max]
    g1 = np.clip(lr[:, 0] - lefty[0], 0, None)
    g2 = np.clip(righty[1] - lr[:, 1], 0, None)
    belong = g1 < g2
    group1 = np.arange(len(lr))[belong]
    group2 = np.arange(len(lr))[~belong]
    return fun(lr[group1]) + fun(lr[group2])


def minmaxsame(lr):
    width = np.diff(lr, axis=1)
    special = np.argmax(width)
    belong = np.arange(len(lr)) == special
    group1 = np.arange(len(lr))[belong]
    group2 = np.arange(len(lr))[~belong]
    return fun(lr[group1]) + fun(lr[group2])

def parse():
    N = int(input())
    LR = []
    for _ in range(N):
        l, r = map(int, input().split())
        LR.append([l, r])
    return np.array(LR)

def main():
    lr = parse()
    print(max(minmaxsplit(lr), minmaxsame(lr)))
    # print(bruteforce(lr))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import numpy as np


def solve(*args: str) -> str:
    n = int(args[0])
    LR = []
    for a in args[1:]:
        LR.append(tuple(map(int, a.split())))

    L, R = map(np.array, zip(*LR))
    lmax, rmin = max(L), min(R)

    Ml = np.maximum(0, rmin-L)
    Mr = np.maximum(0, R-lmax)
    M = list(zip(Ml.tolist(), Mr.tolist(), LR))
    M.sort(key=lambda x: (x[0], -x[1]))
    _, _, LR = zip(*M)

    Dl = np.array([0]*(n-1))
    Dr = np.array([0]*(n-1))

    ll, lr = 0, 1+10**9
    rl, rr = 0, 1+10**9

    for i in range(n-1):
        l, r = LR[i]
        ll, lr = max(ll, l), min(lr, r)
        Dl[i] = lr-ll+1

        l, r = LR[-i-1]
        rl, rr = max(rl, l), min(rr, r)
        Dr[-i-1] = rr-rl+1

    ret = max(Dl+Dr)

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import numpy as np


def solve(*args: str) -> str:
    n = int(args[0])
    LR = []
    for a in args[1:]:
        LR.append(tuple(map(int, a.split())))

    L, R = map(np.array, zip(*LR))
    lmax, rmin = max(L), min(R)

    Ml = np.maximum(0, rmin-L)
    Mr = np.maximum(0, R-lmax)
    M = list(zip(Mr.tolist(), Ml.tolist(), LR))
    M.sort(key=lambda x: (x[0], -x[1]))
    _, _, LR = zip(*M)

    Dl = np.array([0]*(n-1))
    Dr = np.array([0]*(n-1))

    ll, lr = 0, 1+10**9
    rl, rr = 0, 1+10**9

    for i in range(n-1):
        l, r = LR[i]
        ll, lr = max(ll, l), min(lr, r)
        Dl[i] = lr-ll+1

        l, r = LR[-i-1]
        rl, rr = max(rl, l), min(rr, r)
        Dr[-i-1] = rr-rl+1

    ret = max(Dl+Dr)

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))