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: Runtime Error

Solution code:
from bisect import *
from collections import *
from fractions import gcd
from math import factorial
from itertools import *
from heapq import *



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

value=max([R-L for L,R in LR])
#LR=sorted(LR,key=lambda x:x[1])
LR=sorted(LR,key=lambda x:x[0]*10**9+x[1])
a=2*(10**9)
minRlst=[a for i in range(N)]
minRlst[-1]=LR[-1][1]
maxLlst=[0 for i in range(N)]
maxLlst[0]=LR[0][0]
for i in range(N-2,-1,-1):
    minRlst[i]=min(minRlst[i+1],LR[i][1])
for i in range(1,N):
    maxLlst[i]=max(minRlst[i-1],LR[i][0])
L1,R1=LR[0]
L2,R2=LR[-1][0],minRlst[1]
maxR=from bisect import *
from collections import *
from fractions import gcd
from math import factorial
from itertools import *
from heapq import *



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

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

Submission status: Runtime Error

Solution code:
from bisect import *
from collections import *
from fractions import gcd
from math import factorial
from itertools import *
from heapq import *
import math



N=int(input())
LR=[list(map(int,input().split())) for i in range(N)]
value=max([R-L for L,R in LR])+1
LR=sorted(LR,key=lambda x:x[0])

L1,R1=LR[0]
L2,R2=LR[1]
for i in range(2,N):
    L,R=LR[i]
    L2=L
    R2=min(R2,R)
a=max(R1-L1+1,0)
b=max(R2-L2+1,0)
value=max(value,a+b)

logN=math.log2(N)
#table=[[0 for i in range(logN)] for n in range(N)]
minRlst=[2*(10**10) for i in range(N)]
minRlst[-1]=LR[-1][1]
for i in range(N-2,-1,-1):
    minRlst[i]=min(minRlst[i+1],LR[i][1])
for i in range(1,N-1):
    L,R=LR[i]
    L1,R1=L,min(R1,R)
    R2=minRlst[i+1]
    a=max(R1+1-L1,0)
    b=max(R2+1-L2,0)
    value=max(value,a+b)
print(value)

Submission status: Runtime Error

Solution code:
INFTY = 10**10
def numI(x):
    if len(x)==0:
        return 0
    L = x[0]
    R = x[1]
    return R-L+1
def iS(J1,J2):
    if len(J1)==0:
        L1 = INFTY
        R1 = -INFYT
    else:
        L1 = J1[0]
        R1 = J1[1]
    if len(J2)==0:
        L1 = INFYT
        R1 = -INFTY
    else:
        L2 = J2[0]
        R2 = J2[1]
    if R1<L2 or R2<L1:
        return []
    else:
        return [max(L1,L2),min(R1,R2)]
N = int(input())
A = [list(map(int,input().split())) for _ in range(N)]
I1 = A[0]
I2 = A[1]
for i in range(2,N):
    J = A[i]
    a1 = numI(J)
    a2 = numI(iS(I1,I2))
    a = a1+a2
    b1 = numI(iS(I1,J))
    b2 = numI(I2)
    b = b1+b2
    c1 = numI(I1)
    c2 = numI(iS(I2,J))
    c = c1+c2
    if max(a,b,c)==a:
        I1 = iS(I1,I2)
        I2 = J[:]
    elif max(a,b,c)==b:
        I1 = iS(I1,J)
    else:
        I2 = iS(I2,J)
print(numI(I1)+numI(I2))

Submission status: Runtime Error

Solution code:
def numI(x):
    if len(x)==0:
        return 0
    L = x[0]
    R = x[1]
    return R-L+1
def iS(J1,J2):
    L1 = J1[0]
    R1 = J1[1]
    L2 = J2[0]
    R2 = J2[1]
    if R1<L2 or R2<L1:
        return []
    else:
        return [max(L1,L2),min(R1,R2)]
N = int(input())
A = [list(map(int,input().split())) for _ in range(N)]
I1 = A[0]
I2 = A[1]
for i in range(2,N):
    J = A[i]
    a1 = numI(J)
    a2 = numI(iS(I1,I2))
    a = a1+a2
    b1 = numI(iS(I1,J))
    b2 = numI(I2)
    b = b1+b2
    c1 = numI(I1)
    c2 = numI(iS(I2,J))
    c = c1+c2
    if max(a,b,c)==a:
        I1 = iS(I1,I2)
        I2 = J[:]
    elif max(a,b,c)==b:
        I1 = iS(I1,J)
    else:
        I2 = iS(I2,J)
print(numI(I1)+numI(I2))

Submission status: Runtime Error

Solution code:
import sys
import copy

def input():
    return sys.stdin.readline()

def cal(l):
    #print(l)                                                                        
    max_ = max(l, key=lambda x:x[0])
    min_ = min(l, key=lambda x:x[1])
    return max( (min_[1] - max_[0] + 1, 0) )

if __name__=="__main__":
    n = int(input())
    l = set()
    for _ in range(n):
        l.add(tuple(int(i) for i in input().split()))
    l_1 = set()
    l_2 = copy.deepcopy(l)
    C = 0
    for i in l:
        l_2.remove(i)
        l_1.add(i)
        c = cal(l_1) + cal(l_2)
        if c > C:
            C = c
        else:
            l_2.add(i)
            l_1.remove(i)
    print(C)

Submission status: Runtime Error

Solution code:
import sys
import copy

def input():
    return sys.stdin.readline()

def cal(l):
    #print(l)                                                                        
    max_ = max(l, key=lambda x:x[0])
    min_ = min(l, key=lambda x:x[1])
    return max( (min_[1] - max_[0] + 1, 0) )

if __name__=="__main__":
    n = int(input())
    l = []
    for _ in range(n):
        l.append([int(i) for i in input().split()])
    l_1 = []
    l_2 = copy.deepcopy(l)
    C = 0
    for i in l:
        l_2.remove(i)
        c = cal(l_1+[i]) + cal(l_2)
        if c > C:
            l_1.append(i)
            C = c
        else:
            l_2.append(i)
    print(C)

Submission status: Runtime Error

Solution code:
from copy import deepcopy

def joy(a, b):
    return max(b-a+1, 0)

def joyls(ls):
    r = min(ls, key=lambda x: x[1])[1]
    l = max(ls, key=lambda x: x[0])[0]
    return joy(l, r)


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

# same
ls1 = deepcopy(ls)
lsa = list()
lsb = list()

minr = ls1.index(min(ls1, key=lambda x: x[1]))
maxl = n-2

lsa.append(ls1.pop(minr))
lsa.append(ls1.pop(maxl))

maxlen = ls1.index(max(ls1, key=lambda x: joy(x[1], x[0])))

lsb.append(ls1.pop(maxlen))
lsa.extend(ls1)

ans = joyls(lsa) + joyls(lsb)

# different
ls1 = deepcopy(ls)

for i in range(1, n):
    ans = max(ans, joyls(ls1[:i])+joyls(ls1[i:]))

print(ans)

Submission status: Runtime Error

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]
    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: Runtime Error

Solution code:
from heapq import *
from collections import *

N = int(input())
L = [0] * N
R = [0] * N
for i in range(N):
    L[i], R[i] = map(int, input().split())

A = 0
for i in range(N):
    if R[i] < R[A]:
        A = i

v = []
for i in range(N):
    if i == A:
        continue
    v.append((L[i], R[i]))

v.sort(key=lambda i: i[0])
v.reverse()

l_max, r_min = v[0]

ans = r_min - l_max + 1 + max(0, R[A] - max(L[A], v[1][0]) + 1)

for i in range(2, N - 1):
    l_max = max(l_max, v[i - 1][0])
    r_min = min(r_min, v[i - 1][1])
    ans = max(ans, r_min - l_max + 1 + max(0, R[A] - max(L[A], v[i][0]) + 1))

print(ans)

Submission status: Runtime Error

Solution code:
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

const int N = 1e5 + 10;

pair<int, int> s[N];
int x[N], y[N];
int n;

int solve(int a, int b, int c, int d) {
  if (a > b) return max(0, d-c+1);
  if (c > d) return max(0, b-a+1);
  return (b-a+1) + (d-c+1);
}

int main() {

  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> s[i].first >> s[i].second;
  }

  sort(s, s+n);
  
  for (int i = n-1, a = 0, b = (int) 1e9; i >= 0; --i) {
    a = max(a, s[i].first);
    b = min(b, s[i].second);
    x[i] = a;
    y[i] = b;
  }

  int mn = (int) 1e9;
  int ans = 0;
  for (int i = 0; i < n-1; ++i) {
    mn = min(mn, s[i].second);
    ans = max(ans, solve(s[i].first, mn, x[i+1], y[i+1]));
  }

  cout << ans << endl;

  return 0;
}

Submission status: Runtime Error

Solution code:
import sys
from operator import itemgetter
input = sys.stdin.readline

_n, *lrlist = map(int, open(0).read().split())
Lp, Rq = max(lrlist[::2]), min(lrlist[1::2])

st = sorted([(max(r - Lp + 1, 0), max(Rq - l + 1, 0)) for l, r in lrlist])
ans = max([r - l + 1 for l, r in lrlist]) + max(Rq - Lp + 1, 0)

for index, (a, b) in enumerate(st):
    if index:
        continue


for i in range(1, _n):
    s, t = st[:i], st[i:]
    min_b, min_a = sorted(s, key=itemgetter(1))[0][1], t[0][0]

    ans = max(min_a + min_b, ans)

print(ans)

Submission status: Runtime Error

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 = float('INF')

#A
def A():
    s = S()
    n = len(s)
    Llis = [0] * (n + 1)
    Rlis = [0] * (n + 1)
    for i in range(n):
        if s[i] == "<":
            Llis[i + 1] = 1
        else:
            Rlis[i] = 1
    for i in range(n):
        if Llis[i + 1] == 0:
            continue
        Llis[i + 1] += Llis[i]
    for i in range(n):
        if Rlis[-i - 2] == 0:
            continue
        Rlis[-i - 2] += Rlis[-i - 1]
    ans = 0
    for i in range(n + 1):
        ans += max(Rlis[i], Llis[i])
    print(ans)
    return

#B
def B():
    n = II()
    LR = LIR(n)
    LR.sort(key=lambda x: x[1]-x[0], reversed=True)
    ans = [[LR[0][0], LR[0][1] + 1], [LR[1][0], LR[1][1] + 1]]
    for i in range(2,n):
        l, r = LR[i]
        r += 1
        a12 = min(ans[0][1], ans[1][1]) - max(ans[0][0], ans[1][0])
        a12 = (a12 > 0) * a12 + r - l
        a1lr = min(ans[0][1], r) - max(ans[0][0], l)
        a1lr = (a1lr > 0) * a1lr + ans[1][1] - ans[1][0]
        a2lr = min(ans[1][1], r) - max(ans[1][0], l)
        a2lr = (a2lr > 0) * a2lr + ans[0][1] - ans[0][0]
        res = [(a12, 0), (a1lr, 1), (a2lr, 2)]
        res.sort(reverse=True)
        if res[0][1] == 0:
            ans[0] = [max(ans[0][0], ans[1][0]), min(ans[0][1], ans[1][1])]
            ans[1] = [l, r]
        elif res[0][1] == 1:
            ans[0] = [max(ans[0][0], l), min(ans[0][1], r)]
        else:
            ans[1] = [max(ans[1][0], l), min(ans[1][1], r)]
    a = ans[0][1] - ans[0][0]
    b = ans[1][1] - ans[1][0]
    print((a > 0) * a + (b > 0) * b)

    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    B()

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

N = int(input())
L, R = [], []
length = []
for i in range(N):
	Li, Ri = map(int,input().split())
	L.append(Li)
	R.append(Ri)
	length.append(Ri-Li)

sindL = sorted(range(N), key=lambda k: L[k])
sindR = sorted(range(N), key=lambda k: R[k])
sind_len = sorted(range(N), key=lambda k: length[k])

indLmax = sindL[-1]
indRmin = sindR[0]

if indLmax==indRmin:
	ans = R[indRmin]-L[indLmax]+max(length)+2
else:
	lenmax_ind = sind_len[-1]
	if lenmax_ind==indLmax or lenmax_ind==indRmin:
		lenmax_ind = sind_len[-2]
		if lenmax_ind==indLmax or lenmax_ind==indRmin:
			lenmax_ind = sind_len[-3]
	ans = R[indRmin]-L[indLmax]+length[lenmax_ind]+2

	Qind = [0]*N
	Qind[indRmin] = 1
	ri = 1
	for li in range(0,N-1):
		QL, QR = L[sindL[li]], R[indRmin]
		Qind[sindL[li]] = 1
		while Qind[sindR[ri]]==1:
			ri += 1
			if ri==N: break
		PL, PR = L[indLmax], R[sindR[ri]]

		ans = max(ans,PR-PL+QR-QL+2)

print(ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 18
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n = I()
lr_list = LIR(n)
lr_list.sort(key=lambda x:x[1], reverse=True)
lr_list.sort(key=lambda x:x[0])
max_l1 = lr_list[-1][0]
min_r1 = INF


for i, (l, r) in enumerate(lr_list):
    if r < min_r1:
        min_r1 = r
        min_r_ind = i


max_diff = 0
for i in range(n - 1):
    if i == min_r_ind:
        continue
    max_diff = max(max_diff, lr_list[i][1] - lr_list[i][0] + 1)


ans = max(0, min_r1 -  max_l1 + 1) + max_diff
min_r2 = lr_list[-1][1]
for j in range(n - 2, -1, -1):
    if j == min_r_ind:
        continue
    max_l2 = lr_list[j][0]
    ans = max(ans, max(min_r1 - max_l2 + 1, 0) + max(min_r2 - max_l1 + 1, 0))
    min_r2 = min(min_r2, lr_list[j][1])

ans = max(ans, max(min_r1 - max_l2 + 1, 0) + max(min_r2 - max_l1 + 1, 0))




print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

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

def quicksort(x):
    if x==[]: return []

    smallerSorted = quicksort([a for a in x[1:] if (a[0] < x[0][0] or (a[0] == x[0][0] and a[1] >= x[0][1])])
    biggerSorted = quicksort([a for a in x[1:] if (a[0] > x[0][0] or (a[0] == x[0][0] and a[1] < x[0][1]))])

    return(smallerSorted+[x[0]]+biggerSorted)

LR = quicksort(LR)

ans = [0] * (n+1)
temp = 10 ** 9
i = 1
for L, R in LR:
    temp = min(temp, R)
    if L > temp:
        break
    ans[i] = temp - L + 1
    i += 1
#print(ans)
temp = 10 ** 9
i = n - 1
L = LR[-1][0]
for x, R in reversed(LR):
    temp = min(temp, R)
    if L > temp:
        break
    ans[i] += temp - L + 1
    i -= 1

print(max(ans))

Submission status: Runtime Error

Solution code:
N = int(input())
LR = []
p = 0
max_L = 0
q = 0
min_R = 10**9 + 1

for i in range(N):
    L, R = map(int, input().split())
    R += 1
    LR.append((L, R))
    if L > max_L:
        p = i
        max_L = L
    if R < min_R:
        q = i
        min_R = R

if p == q:
    print(max(r - l for l, r in LR) + max(min_R - max_L, 0))
    exit()

L1, R1 = LR[p]
L2, R2 = LR[q]
LR = [(L, R) for i, (L, R) in enumerate(LR) if i != p and i != q]
LR.sort(key=lambda x: (x[1], x[0]), reverse=True)

ans1 = max(R - L for L, R in LR) + max(min_R - max_L, 0)

n = len(LR) + 1
min_sr = [R1] * n
max_tl = [L2] * n

for i in range(1, n):
    min_sr[i] = min(min_sr[i-1], LR[i-1][1])
    max_tl[n-i-1] = max(max_tl[n-i], LR[n-i-1][0])

ans2 = max(max(r - L1, 0) + max(R2 - l, 0) for r, l in zip(min_sr, max_tl))

print(max(ans1, ans2))

Submission status: Runtime Error

Solution code:
def calc(s, t):
    t_l = [x[0] for x in t]
    s_r = [x[1] for x in s]
    return max(min(s_r) - max_L, 0) + max(min_R - max(t_l), 0)


N = int(input())
sections = []

L, R = map(int, input().split())
sections.append((L, R + 1))
p = 0
max_L = L
q = 0
min_R = R

for i in range(1, N):
    L, R = map(int, input().split())
    R += 1
    sections.append((L, R))
    if L > max_L:
        p = i
        max_L = L
    if R < min_R:
        q = i
        min_R = R

s = [sections[p]]
t = [sections[q]]
sections.pop(p)
sections.sort(key=lambda x: (x[1], x[0]))
sections.pop(0)  # q
s = sections + s

ranges = [x[1] - x[0] for x in sections]
ans1 = max(ranges) + max(min_R - max_L, 0)

ans2 = calc(s, t)

for i in range(len(sections)):
    t += [s.pop(0)]
    ans2 = max(ans2, calc(s, t))

print(max(ans1, ans2))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
n = int(input())
p = sorted(list(map(int, input().split())) for _ in range(n))

lmax = n - 1
rmin = 0
for i in range(n):
    if p[i][1] <= p[rmin][1]:
        rmin = i

ans = 0

# same(lmax, rmin)
dmax = 0
for i in range(n):
    if i == lmax or i == rmin:
        continue
    if p[i][1] - p[i][0] > p[dmax][1] - p[dmax][0]:
        dmax = i
    d1 = max(0, p[rmin][1] - p[lmax][0] + 1)
    d2 = max(0, p[dmax][1] - p[dmax][0] + 1)
ans = max(ans, d1 + d2)

# !same(lmax, rmin)
m = lmax
for i in range(rmin, lmax)[::-1]:
    if p[i + 1][1] < p[m][1]:
        m = i + 1
    d1 = max(0, p[rmin][1] - p[i][0] + 1)
    d2 = max(0, p[m][1] - p[lmax][0] + 1)
    ans = max(ans, d1 + d2)

print(ans)

Submission status: Runtime Error

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

ML = max(LR)[0]
mR = min(LR,key=lambda x:x[1])[1]

ans = max(ML-mR+1,0)+max([LR[i][1]-LR[i][0]+1 for i in range(N)])
LR.sort(key=lambda x:[x[1],x[0]])

L_ = [0]*N
for i in range(N):
    L_[i] = max(L[i],L_[i-1])

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

print(ans)

Submission status: Runtime Error

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


ML = max(LR)[0]
mR = min(LR,key=lambda x:x[1])[1]

ans = max(ML-mR+1,0)+max([LR[i][1]-LR[i][0]+1 for i in range(N)])
LR.sort(key=lambda x:[x[1],x[0]])

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

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

print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
max_l = 0
max_len = 0
min_r = 1001001001
min_len = 0
l_i = 0
r_i = 0
p = []
longest = 0
for i in range(n):
  l, r = map(int, input().split())
  p.append([l, r])
  if l - r + 1 > longest:
    longest = l - r + 1 
  if l > max_l:
    max_l = l
    l_i = i
  elif l == max_l:
    if r - l > max_len:
      l_i = i
      max_len = r - l
  if r < min_r:
    min_r = r
    r_i = i
  elif r == min_r:
    if r - l > min_len:
      r_i = i
      min_len = r - l
g1 = []
g2 = []
g1.append(p[l_i])
g2.append(p[r_i])
g1_r = p[l_i][1]
g1_l = p[l_i][0]
g2_r = p[r_i][1]
g2_l = p[r_i][0]
#最小rと最大rを別々のグループに入れる
for i in range(n):
  if i == l_i or i == r_i:
    continue
  else:
    if min(p[i][1] - g1_r, 0) < min(g2_l - p[i][0], 0):
      g2.append(p[i])
      g2_l = max(g2_l, p[i][0])
    else:
      g1.append(p[i])
      g1_r = min(g1_r, p[i][1])
ans = max(g1_r - g1_l + 1, 0) + max(g2_r -g2_l + 1, 0)
#ans2 = max(g2_r - g1_l + 1, 0) + longest

print(max(ans, ans2))

Submission status: Runtime Error

Solution code:
N=int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
import numpy as np
A=[0,0]
B=[0,10**9]

m=0
for i in LR:
  x = i[1]-i[0]
  if x>m:
    m=x
    A=i
LR.remove(A)
A_L=[A[0]]
A_R=[A[1]]
B_L=[]
B_R=[]
for i in LR:
  B_L.append(i[0])
  B_R.append(i[1])
    
for i in LR:
  a=i[0]
  b=i[1]
  x=min(B_R)-max(B_L)
  B_L.remove(a)
  B_R.remove(b)
  x=min(B_R)-max(B_L)-x
  y=min(A_R)-max(A_L)
  y=min(min(A_R),b)-max(max(A_L),a)-y
  if x+y>=1:
    A_L.append(a)
    A_R.append(b)
  else:
    B_L.append(a)
    B_R.append(b)
    
print(min(B_R)-max(B_L)+min(A_R)-max(A_L)+2)

Submission status: Runtime Error

Solution code:
# coding: utf-8
from functools import lru_cache
import sys


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

    dp = DP(LR)

    sys.setrecursionlimit(10**5)
    return str(dp.search_max(0, 0, 10**9, 0, 10**9))


class DP:
    def __init__(self, LR: list):
        self.LR = LR

    @lru_cache(maxsize=None)
    def search_max(self, index: int, l1: int, r1: int, l2: int, r2: int)\
            -> int:
        ret = 0

        if index < len(self.LR):
            l, r = self.LR[index]
            ret = max(
                self.search_max(index+1, max(l, l1), min(r, r1), l2, r2),
                self.search_max(index+1, l1, r1, max(l, l2), min(r, r2))
            )
        else:
            if l1 == 0 or l2 == 0:
                ret = 0
            else:
                ret = max(0, (r1-l1)) + max(0, (r2-l2) + 2)

        return ret


if __name__ == "__main__":
    n = input()
    print(solve(*([n]+[input() for _ in range(int(n))])))

Submission status: Runtime Error

Solution code:
# 一番長いLRが最低の楽しさ
# 一番長いLRと重なるのが一番少ないものはもう一つにする
# 一番長いLRが最低の楽しさ 一番長いLRが複数ある場合どうする？
# 一番長いLRと重なるのが一番少ないものはもう一つにする
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)][::-1]
LR.sort(key=lambda x: x[1]-x[0], reverse=True)
ma = LR[0][1] - LR[0][0] + 1
left_ma = LR[0][0]
right_ma = LR[0][1]

ma2 = ma
another = 10 ** 9
another_length = 0 #重なっていない長さ
LR.pop(0)

another_length = LR[1][1] - LR[1][0] + 1
left_an = LR[1][0]
right_an = LR[1][1]

point = ma + another_length
LR.pop(1)
for l, r in LR:
    if max(0, min(right_ma, r) - max(left_ma, l)) + another_length < ma + max(0, min(right_an, r) - max(left_an, l)):
        # anotherのグループにいれる
        another_length = max(0, min(right_an, r) - max(left_an, l) + 1)
        point = ma + another_length
        right_an = min(r, right_an)
        left_an = max(l, left_an)
        #print(right_an, left_an)
    else:
        ma = max(0, min(right_ma, r) - max(left_ma, l) + 1)
        point = ma + another_length
        right_ma = min(r, right_ma)
        left_ma = max(l, left_ma)

print(max(ma2, point))

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
m = map(int,read().split())
LR = list(zip(m,m))

if N==2:
    L1,R1 = LR[0]
    L2,R2 = LR[1]
    answer = (R1-L1+1) + (R2-L2+1)
    print(answer)
    exit()

# 片方に集める場合
max_width = max(R-L+1 for L,R in LR)

LR.sort()

INF=10**18
# Rが最小のもの
i = -1
opt_R = INF
for n,(L,R) in enumerate(LR):
    if opt_R>=R:
        opt_R=R
        i=n
j = -1
opt_L = -INF
for n,(L,R) in enumerate(LR):
    if opt_L<=L:
        opt_L=L
        j=n

if i==j:
    L,R = LR[i]
    answer = max_width + (R-L+1)
    print(answer)
    raise Exception
    exit()

L1,R1 = LR[i]; L2,R2 = LR[j]

LR = [(L,R) for n,(L,R) in enumerate(LR) if n != i and n != j]

LR.sort()

n = len(LR)
dpl = [(-INF,INF)]*(n+1)
dpr = [(-INF,INF)]*(n+1)

for i in range(n):
    a,b = dpl[i]
    L,R = LR[i]
    dpl[i+1] = (max(a,L),min(b,R))
for i in range(n,0,-1):
    a,b = dpr[i]
    L,R = LR[i-1]
    dpr[i-1] = (max(a,L),min(b,R))

answer = 0
for (a,b),(c,d) in zip(dpl,dpr):
    l1 = max(L1,a); r1 = min(R1,b)
    l2 = max(L2,c); r2 = min(R2,d)
    x = max(0,r1-l1+1) + max(0,r2-l2+1)
    if answer < x:
        answer = x

if answer < max_width:
    answer = max_width

print(answer)

Submission status: Runtime Error

Solution code:
def cmnrng(x, y):
    if x[0] < y[0]:
        a = x
        b = y
    else:
        a = y
        b = x
        
    if a[1] < b[0]:
        return([])
    elif a[1] > b[1]:
        return(b)
    else:
        return([b[0], a[1]])
    
def lenrng(l):
    if l == []:
        return 0
    else:
        return l[1] - l[0] + 1
    
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]

G1 = LR[0]
common = [0] * N
for i in range(N):
    cmn = cmnrng(LR[i], G1)
    common[i] = lenrng(cmn)

idxG2 = common.index(min(common))
G2 = LR[idxG2]

for i in range(1, N):
    if i == idxG2:
        pass
    else:
        tmpG1 = cmnrng(G1, LR[i])
        tmpG2 = cmnrng(G2, LR[i])
        case1 = lenrng(tmpG1) + lenrng(G2)
        case2 = lenrng(tmpG2) + lenrng(G1)
        if case1 >= case2:
            G1 = tmpG1
        else:
            G2 = tmpG2

print(lenrng(G1) + lenrng(G2))

Submission status: Runtime Error

Solution code:
# coding: utf-8
from functools import lru_cache


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

    dp = DP(LR)

    return str(dp.search_max(0, 0, 10**9, 0, 10**9))


class DP:
    def __init__(self, LR: list):
        self.LR = LR

    @lru_cache(maxsize=None)
    def search_max(self, index: int, l1: int, r1: int, l2: int, r2: int)\
            -> int:
        ret = 0

        if index < len(self.LR):
            l, r = self.LR[index]
            ret = max(
                self.search_max(index+1, max(l, l1), min(r, r1), l2, r2),
                self.search_max(index+1, l1, r1, max(l, l2), min(r, r2))
            )
        else:
            if l1 == 0 or l2 == 0:
                ret = 0
            else:
                ret = max(0, (r1-l1)) + max(0, (r2-l2) + 2)
        # print((l1, r1, l2, r2))
        return ret


if __name__ == "__main__":
    n = input()
    print(solve(*([n]+[input() for _ in range(int(n))])))

Submission status: Runtime Error

Solution code:
def get_p(l1,l2):
    l3 = [0,0]
    l3[0] = max(l1[0],l2[0])
    l3[1] = min(l1[1],l2[1])
    
    return l3
    
def add_a_b(a,b,lis,i,n):
    if i == n:
        global max_num
        num = a[1] - a[0] - b[0] + 2 + b[1]
        max_num = max(max_num,num)
        return
    
    # aに追加
    pre_a0 = a[0]
    pre_a1 = a[1]
    if a == [-1,-1]:
        a[0] = lis[i][0]
        a[1] = lis[i][1]
    else:
        a = get_p(a,lis[i])
        
    if a[0] <= a[1]:
        add_a_b(a,b,lis,i+1,n)
    a[0] = pre_a0
    a[1] = pre_a1
    
    # bに追加
    pre_b0 = b[0]
    pre_b1 = b[1]
    
    if b == [-1,-1]:
        b[0] = lis[i][0]
        b[1] = lis[i][1]
    else:
        b = get_p(b,lis[i])
        
    if b[0] <= b[1]:
        add_a_b(a,b,lis,i+1,n)
    b[0] = pre_b0
    b[1] = pre_b1
    
n = int(input())
lis = [0 for i in range(n)]

for i in range(n):
    lis[i] = [int(x) for x in input().split()]
    
a = [-1,-1]
b = [-1,-1]

max_num = 0
i = 0
add_a_b(a,b,lis,i,n)
print(max_num)

Submission status: Runtime Error

Solution code:
import sys

def answer():
    input = sys.stdin.readline
    N = int(input())
    questions = [list(map(int, input().split())) for _ in range(N)]

    questions.sort(key=lambda x: x[0], reverse=True)
    distances = [q[1]-q[0]+1 for q in questions]

    index_most_fun = distances.index(max(distances))
    most_fun_q = questions.pop(index_most_fun)

    questions.sort(key=lambda x: x[0])
    index_worst_fun = distances.index(min(distances))
    most_far_q = questions.pop(index_worst_fun)

    def calc_overlap(q1, q2):
        return max(min(q1[1], q2[1]) - max(q1[0], q2[0]), 0)

    def calc_overlap_for_most_fun(q):
        return calc_overlap(q, most_fun_q)

    def calc_diff(q):
        return abs(q[0] - most_fun_q[0] + q[1] - most_fun_q[1])

    def calc_overlap_for_most_far(q):
        return calc_overlap(q, most_far_q)

    def calc_score(q):
        return max(q[1] - q[0] + 1, 0)

    fun = most_fun_q
    far = most_far_q
    score_fun = calc_score(fun)
    score_far = calc_score(far)

    for q in questions:
        diff_fun = score_fun - calc_overlap_for_most_fun(q)
        diff_far = score_far - calc_overlap_for_most_far(q)

        if diff_fun > diff_far:
            far = [max(q[0], far[0]), min(q[1], far[1])]
            score_far = calc_score(far)
        else:
            fun = [max(q[0], fun[0]), min(q[1], fun[1])]
            score_fun = calc_score(fun)

    print(score_fun + score_far)


if __name__ == '__main__':
    answer()