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:
N, *LR = map(int, open(0).read().split())
L, R = LR[::2], LR[1::2]

Lp = max(L)
Rq = min(R)

A = sorted(max(0, r - Lp + 1) for r in R)
B = sorted(-max(0, Rq - l + 1) for l in L)

mi = float("inf")
ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, Rq - Lp + 1)

for a, b in zip(A[1:], B):
    mi = min(mi, -b)
    ma = max(ma, mi + a)

print(ma)

Submission status: Accepted

Solution code:
N, *LR = map(int, open(0).read().split())
L, R = LR[::2], LR[1::2]

max_l = max(L)
min_r = min(R)

A = sorted(max(0, r - max_l + 1) for r in R)
B = sorted(-max(0, min_r - l + 1) for l in L)

mi = float("inf")
ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)

for i in range(N - 1):
    mi = min(mi, -B[i])
    ma = max(ma, mi + A[i + 1])

print(ma)

Submission status: Accepted

Solution code:
N, *LR = map(int, open(0).read().split())
L, R = LR[::2], LR[1::2]

max_l = max(L)
min_r = min(R)

ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
ab.sort()

mi = float("inf")
ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)

for i in range(N - 1):
    mi = min(mi, -ab[i][1])
    ma = max(ma, mi + ab[i + 1][0])

print(ma)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, *LR = map(int, stdin.buffer.read().split())
    L, R = LR[::2], LR[1::2]

    max_l = max(L)
    min_r = min(R)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)

    for (_, r), (l, _) in zip(ab, ab[1:]):
        mi = -r if mi > -r else mi
        ma = mi + l if ma < mi + l else ma

    print(ma)

main()

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, *LR = map(int, stdin.buffer.read().split())
    L, R = LR[::2], LR[1::2]

    max_l = max(L)
    min_r = min(R)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)

    for (_, r), (l, _) in zip(ab, ab[1:]):
        mi = min(mi, -r)
        ma = max(ma, mi + l)

    print(ma)

main()

Submission status: Accepted

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

    max_l = max(L)
    min_r = min(R)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)
    for i in range(N - 1):
        mi = min(mi, -ab[i][1])
        ma = max(ma, mi + ab[i + 1][0])

    print(ma)

main()

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    input = stdin.buffer.readline

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

    max_l = max(L)
    min_r = min(R)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)
    for i in range(N - 1):
        mi = min(mi, -ab[i][1])
        ma = max(ma, mi + ab[i + 1][0])

    print(ma)

main()

Submission status: Accepted

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 N==2:
	ans = sum(length)+2
else:
	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 = max(0,R[indRmin]-L[indLmax]+1)+length[lenmax_ind]+1

		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
			PL, PR = L[indLmax], R[sindR[ri]]

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

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, *LR = map(int, stdin.buffer.read().split())
    L, R = LR[::2], LR[1::2]

    max_l = max(L)
    min_r = min(R)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)
    for i in range(N - 1):
        mi = min(mi, -ab[i][1])
        ma = max(ma, mi + ab[i + 1][0])

    print(ma)

main()

Submission status: Accepted

Solution code:
def main():
    N, *LR = map(int, open(0).read().split())
    L, R = LR[::2], LR[1::2]

    max_l = max(L)
    min_r = min(R)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in zip(L, R)]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)
    for i in range(N - 1):
        mi = min(mi, -ab[i][1])
        ma = max(ma, mi + ab[i + 1][0])

    print(ma)

main()

Submission status: Accepted

Solution code:
def main():
    N, *LR = map(int, open(0).read().split())
    LR = list(zip(*[iter(LR)] * 2))

    max_l = max(l for l, _ in LR)
    min_r = min(r for _, r in LR)

    ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in LR]
    ab.sort()

    mi = float("inf")
    ma = max(r - l + 1 for l, r in LR) + max(0, min_r - max_l + 1)
    for i in range(N - 1):
        mi = min(mi, -ab[i][1])
        ma = max(ma, mi + ab[i + 1][0])

    print(ma)

main()

Submission status: Accepted

Solution code:
N, *LR = map(int, open(0).read().split())
LR = list(zip(*[iter(LR)] * 2))

max_l = max(l for l, _ in LR)
min_r = min(r for _, r in LR)

ab = [(max(0, r - max_l + 1), -max(0, min_r - l + 1)) for l, r in LR]
ab.sort()

mi = float("inf")
ma = max(r - l + 1 for l, r in LR) + max(0, min_r - max_l + 1)
for i in range(N - 1):
    mi = min(mi, -ab[i][1])
    ma = max(ma, mi + ab[i + 1][0])

print(ma)

Submission status: Accepted

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




if n == 2:
    print(lr_list[0][1] - lr_list[0][0] + 1 + lr_list[1][1] - lr_list[1][0] + 1)


else:
    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])


    max_l2 = lr_list[min_r_ind][0]
    ans = max(ans, max(min_r1 - max_l2 + 1, 0) + max(min_r2 - max_l1 + 1, 0))
    print(ans)

Submission status: Accepted

Solution code:
N=int(input())
LR=sorted([list(map(int,input().split())) for i in range(N)])
x,y,z,w=[0]*(N+1),[10**9+1]*(N+1),[0]*(N+1),[10**9+1]*(N+1)
l=0
for i in range(N):
    x[i+1],y[i+1]=max(x[i],LR[i][0]),min(y[i],LR[i][1])
    z[-i-2],w[-i-2]=max(z[-i-1],LR[-i-1][0]),min(w[-i-1],LR[-i-1][1])
    l=max(l,LR[i][1]-LR[i][0]+1)
print(max([max(0,y[-1]-x[i]+1)+max(0,w[i]-z[0]+1) for i in range(1,N)]+[l+max(0,y[-1]-z[0]+1)]))

Submission status: Accepted

Solution code:
from operator import itemgetter

N = int(input())
L = [[int(x) for x in input().split()] for _ in range(N)]


for i in range(N):
    L[i].append(L[i][1]-L[i][0])
    
L.sort()
#L.sort(key=itemgetter(1))
#L.sort(key=itemgetter(2))
    

la = L[0][0]
ra = L[0][1]
lb = L[1][0]
rb = L[1][1]
ans = L[-1][2]+1
for i in range(2, N):
    ta = max(0, min(ra, L[i][1])-max(la, L[i][0])+1) + rb-lb+1
    tb = max(0, min(rb, L[i][1])-max(lb, L[i][0])+1) + ra-la+1
    tc = max(0, min(ra, rb)-max(la,lb)+1) + L[i][1]-L[i][0]+1
    if max(ta, tb, tc) == ta:
        la = max(la, L[i][0])
        ra = min(ra, L[i][1])
    elif max(ta, tb, tc) == tb:
        lb = max(lb, L[i][0])
        rb = min(rb, L[i][1])
    else:
        la = max(la, lb)
        ra = min(ra, rb)
        lb = L[i][0]
        rb = L[i][1]
        
ans = max(ans, max(0, ra-la+1) + max(0, rb-lb+1))


print(ans)

Submission status: Accepted

Solution code:
import numpy as np

n = int(input())
l = []
r = []
for i in range(n):
    li, ri = map(int, input().split())
    l.append(li)
    r.append(ri+1)

arglmax = l.index(max(l))
argrmin = r.index(min(r))
num = 0
for i in range(n):
    num = max(r[i] - l[i], num)
ans1 = num + max(0, r[argrmin]-l[arglmax])

lst = [l, r]
lst = list(np.array(lst).T)
lst = sorted(lst, key=lambda x: (x[0]), reverse=True)
lst = sorted(lst, key=lambda x: (x[1]))
lst = list(np.array(lst).T)
sorted_l = list(lst[0])
sorted_r = list(lst[1])

sorted_r_minus_lmax = list(np.array(sorted_r)-l[arglmax])
mini = sorted_r_minus_lmax[n-1]
for i in range(1, n):
    mini = min(mini, sorted_r_minus_lmax[n-1-i])
    sorted_r_minus_lmax[n-1-i] = mini
rmin_minus_sorted_l = list(r[argrmin]-np.array(sorted_l))
mini = rmin_minus_sorted_l[0]
for i in range(1, n):
    mini = min(mini, rmin_minus_sorted_l[i])
    rmin_minus_sorted_l[i] = mini

ans2 = 0
for i in range(n-1):
    ai = max(0, sorted_r_minus_lmax[i+1])
    bi = max(0, rmin_minus_sorted_l[i])
    ans2 = max(ans2, ai+bi)

print(max(ans1, ans2))

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1

def main():
    inf = 10 ** 10
    n = int(input())
    lr = [list(map(int, input().split())) for _ in range(n)]
    biggest_l = max(l for l, r in lr)
    smallest_r = min(r for l, r in lr)
    mx = max(r - l + 1 for l, r in lr) + max(smallest_r - biggest_l + 1, 0)
    ab = [[max(0, r - biggest_l + 1), max(0, smallest_r - l + 1)] for l, r in lr]
    ab.sort(key=lambda x: (x[0], -x[1]))
    # print(ab)
    min_r = 10 ** 10
    for i in range(n - 1):
        if ab[i][1] < min_r: min_r = ab[i][1]
        cur = min_r + ab[i + 1][0]
        if cur > mx: mx = cur
    print(mx)

main()

Submission status: Accepted

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)

e = [[] for _ in range(n+2)]

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

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

res = max(ans)
for L, R in LR:
    res = max(res, R - L + 1 + ans[0])

#print(LR)
#print(ans)
print(res)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
from operator import itemgetter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 **18
MOD = 10 ** 9 + 7

class SegTree:
    """
    セグメント木
    1.update:  i番目の値をxに更新する
    2.query: 区間[l, r)の値を得る
    """

    def __init__(self, n, func, intv, A=[]):
        """
        :param n: 要素数(0-indexed)
        :param func: 値の操作に使う関数(min, max, add, gcdなど)
        :param intv: 要素の初期値(単位元)
        :param A: 初期化に使うリスト(オプション)
        """
        self.n = n
        self.func = func
        self.intv = intv
        # nより大きい2の冪数
        n2 = 1
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [self.intv] * (n2 << 1)
        # 初期化の値が決まっている場合
        if A:
            # 1段目(最下段)の初期化
            for i in range(n):
                self.tree[n2+i] = A[i]
            # 2段目以降の初期化
            for i in range(n2-1, -1, -1):
                self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1])

    def update(self, i, x):
        """
        i番目の値をxに更新
        :param i: index(0-indexed)
        :param x: update value
        """
        i += self.n2
        self.tree[i] = x
        while i > 1:
            self.tree[i >> 1] = x = self.func(x, self.tree[i ^ 1])
            i >>= 1
 
    def query(self, a, b):
        """
        [a, b)の値を得る
        :param a: index(0-indexed)
        :param b: index(0-indexed)
        """
        l = a + self.n2
        r = b + self.n2
        s = self.intv
        while l < r:
            if r & 1:
                r -= 1
                s = self.func(s, self.tree[r])
            if l & 1:
                s = self.func(s, self.tree[l])
                l += 1
            l >>= 1
            r >>= 1
        return s

    def get(self, i):
        """ 一点取得 """
        return self.tree[i+self.n2]

N = INT()
LR = []
for i in range(N):
    l, r = MAP()
    LR.append((l, r))

LR.sort(key=itemgetter(0))
L, R = zip(*LR)
st1 = SegTree(N, max, -INF, L)
st2 = SegTree(N, min, INF, R)

ans = 0
# 1区間だけ独立させるケース
for i in range(N):
    l1 = st1.get(i)
    r1 = st2.get(i)
    l2 = max(st1.query(0, i), st1.query(i+1, N))
    r2 = min(st2.query(0, i), st2.query(i+1, N))
    ans = max(ans, max(r1-l1+1, 0) + max(r2-l2+1, 0))

# ある場所から半分に分けるケース
for i in range(N-1):
    l1 = st1.query(0, i+1)
    r1 = st2.query(0, i+1)
    l2 = st1.query(i+1, N)
    r2 = st2.query(i+1, N)
    ans = max(ans, max(r1-l1+1, 0) + max(r2-l2+1, 0))

print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline

    n = int(input())
    dg = 10**10
    lr = []
    for _ in [0]*n:
        lll,rrr = map(int,input().split())
        lr.append(lll*dg+rrr)
    lr.sort()

    #mirl[i],marl[i]:R0~Riのmin,max
    mirl = [10**10]*n
    marl = [0]*n
    for i,e in enumerate(lr):
        mirl[i] = min(mirl[i-1],e%dg)
        marl[i] = max(marl[i-1],e%dg)
    
    #mirr[i]:Ri~Rn-1のmin
    mirr = [0]*n
    mirr[-1] = lr[-1]%dg
    for i in range(n-2,-1,-1):
        mirr[i] = min(mirr[i+1],lr[i]%dg)

    L1 = lr[-1]//dg
    res = (lr[0]%dg - lr[0]//dg+1) + max(0,mirr[1]-L1+1)

    for k in range(n-2,0,-1):
        #print(res)
        L2 = lr[k]//dg
        R1 = mirr[k+1]
        R2 = lr[k]%dg

        restMaxR = marl[k-1]
        restMinR = mirl[k-1]

        #print(L1,L2,R1,R2,restMaxR,restMinR)

        tmp = max(0,R1-L1+1) + max(0,min(restMinR,R2)-L2+1)
        tmp = max(tmp,max(0,min(restMinR,R1)-L1+1) + max(0,R2-L2+1))

        res = max(res,tmp)

    
    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append([x,y])

ps.sort()
for p in ps:
#    p[1] *= -1
    if p == [mx, my]:
        print(my-mx+1+md)
        sys.exit()

for i, (x, y) in enumerate(ps):
    if y == my:
        mmx = x
        del ps[i]
        break

from collections import deque
rs = []
dq = deque()
for i in range(N-1):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] >= ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = max(my-mx+1, 0) + md
r = max(r, max(my - mmx + 1, 0) + max(ps[dq.popleft()][1] - mx + 1, 0))
#SegTree(pys, N-1, 10**9, min)
for i in range(N-2):
    x = max(ps[i][0], mmx)
    if len(dq):
        if i+1 == dq[0]:
            y = ps[dq.popleft()][1] # mx
    #y = min(p[1] for p in ps[i+1:])
#    print(r)
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from operator import itemgetter

n = ni()
lefts = []
rights = []
intervals = []
for _ in range(n):
    l, r = li()
    r += 1
    lefts.append(l)
    rights.append(r)
    intervals.append((l, r))

maxleft = max(lefts)
minright = min(rights)
ans = 0

## (1)最高の左端と最低の右端が同じ集合にあるとき
# 1区間のみを選択
longest = 0
for l, r in intervals:
    if l == maxleft or r == minright:
        continue
    else:
        longest = max(longest, r - l)
ans = longest + max(0, minright - maxleft)

## (2)最高の左端と最低の右端が別の集合にあるとき
intervals = sorted(sorted(intervals, key=itemgetter(1), reverse=True), key=itemgetter(0))

s_maxleft = [intervals[0][0]]
s_minright = [intervals[0][1]]
t_maxleft = [intervals[-1][0]]
t_minright = [intervals[-1][1]]

for idx, (l, r) in enumerate(intervals):
    if idx == 0:
        continue
    s_maxleft.append(max(s_maxleft[-1], l))
    s_minright.append(min(s_minright[-1], r))

for idx, (l, r) in enumerate(intervals[::-1]):
    if idx == 0:
        continue
    t_maxleft.append(max(s_maxleft[-1], l))
    t_minright.append(min(t_minright[-1], r))

t_maxleft = t_maxleft[::-1]
t_minright = t_minright[::-1]

for i in range(n-1):
    ans = max(ans, max(0, s_minright[i] - s_maxleft[i]) + max(0, t_minright[i+1] - t_maxleft[i+1]))

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
INF = float('inf')

L = []
R = []
for _ in range(N):
    l, r = map(int, input().split())
    L.append(l)
    R.append(r)

maxL = max(L)
minR = min(R)

LR = [(minR - l + 1, r - maxL + 1) for l, r in zip(L, R)]
LR.sort()

ans = 0
S = INF
for (_, b), (a, _) in zip(LR, LR[1:]):
    S = min(S, b)
    ans = max(ans, a + S)

# minLとmaxRを一緒にする
for l, r in zip(L, R):
    now = r - l + 1
    now += max(0, minR - maxL + 1)
    ans = max(ans, now)

print(ans)

Submission status: Accepted

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

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

if N == 2:
    print(sum(R - L for L, R in LR))
    exit()

if p == q:
    print(ans1)
    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)

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

Solution code:
#!/usr/bin/env python3
import sys

def solve(N: int, L: "List[int]", R: "List[int]"):
    LR= list(zip(L,R))
    LR.sort(key=lambda x:x[0])

    r_left_max = [] ##index 以下のrightのmin
    for lr in LR:
        if r_left_max:
            r_left_max.append(min(r_left_max[-1],lr[1]))
        else:
            r_left_max.append(lr[1])

    r_right_max = []
    for lr in LR[::-1]:
        if r_right_max:
            r_right_max.append(min(r_right_max[-1],lr[1]))
        else:
            r_right_max.append(lr[1])

    answer = 0
    for i in range(1,N):
        a = 0
        a += max(r_left_max[i-1]-LR[i-1][0]+1,0)
        a += max(r_right_max[N-i-1]-LR[-1][0]+1,0)
        answer = max(a,answer)

    ## 一つとその他の場合。indexがiのものを一つにする
    for i in range(N):
        a =0 
        a+= LR[i][1]-LR[i][0]+1
        if i == N-1:
            min_upper_limit = r_left_max[N-2]
            a+= max(min_upper_limit-LR[N-2][0]+1,0)
        elif i == 0:
            min_upper_limit = r_right_max[N-2]
            a+= max(min_upper_limit-LR[-1][0]+1,0)
        else:
            min_upper_limit = min(r_left_max[i-1],r_right_max[N-i-2])

            a+= max(min_upper_limit-LR[-1][0]+1,0)

        answer = max(a,answer)
    
    print(answer)

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    L = [int()] * (N)  # type: "List[int]"
    R = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        L[i] = int(next(tokens))
        R[i] = int(next(tokens))
    solve(N, L, R)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter as ITEM
input = sys.stdin.readline
N = int(input())
mG = [tuple(map(int, input().split())) for _ in range(N)]

mG.sort(key=ITEM(1), reverse=True)
mG.sort(key=ITEM(0))

INF = 1000100100

vA1 = []
L = -1
R = INF
for l,r in mG[:-1]:
    L = max(L, l)
    R = min(R, r)
    vA1.append(R-L+1)

vA2 = []
L = -1
R = INF
for l,r in mG[:0:-1]:
    L = max(L, l)
    R = min(R, r)
    vA2.append(R-L+1)

M1 = max(a+b for a,b in zip(vA1, vA2[::-1]))

# pick max1
# and all others to 2
k = 0
idm = -1
for i,(l,r) in enumerate(mG):
    d = r-l+1
    if d > k:
        k = d
        idm = i

L = -1
R = INF
for i,(l,r) in enumerate(mG):
    if i==idm:
        continue
    L = max(L, l)
    R = min(R, r)

M2 = k + max(0, R-L+1)

print(max(M1,M2))

Submission status: Accepted

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

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

N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
LR.sort(key=itemgetter(0))

dp = [[[0, 0], [0, 0]] for _ in range(N)]

L0, R0 = LR[0]
L1, R1 = LR[1]
dp[1][0][0] = L0
dp[1][0][1] = R0
dp[1][1][0] = L1
dp[1][1][1] = R1
L, R = max(L0, L1), min(R0, R1)
for i in range(1, N-1):
    l, r = LR[i+1]
    a0 = max(min(dp[i][0][1], r) - max(dp[i][0][0], l)+1, 0) + max(dp[i][1][1] - dp[i][1][0] + 1, 0)
    a1 = max(min(dp[i][1][1], r) - max(dp[i][1][0], l)+1, 0) + max(dp[i][0][1] - dp[i][0][0] + 1, 0)
    a2 = max(R-L+1, 0) + r-l+1
    a = max(a0, a1, a2)
    if a == a2:
        dp[i+1][0][0] = l
        dp[i+1][0][1] = r
        dp[i+1][1][0] = L
        dp[i+1][1][1] = R
    elif a == a0:
        dp[i+1][0][0] = max(dp[i][0][0], l)
        dp[i+1][0][1] = min(dp[i][0][1], r)
        dp[i+1][1][0] = dp[i][1][0]
        dp[i+1][1][1] = dp[i][1][1]
    elif a == a1:
        dp[i+1][0][0] = dp[i][0][0]
        dp[i+1][0][1] = dp[i][0][1]
        dp[i+1][1][0] = max(dp[i][1][0], l)
        dp[i+1][1][1] = min(dp[i][1][1], r)
    L, R = max(L, l), min(R, r)

ans = max(dp[N-1][0][1]-dp[N-1][0][0]+1, 0) + max(dp[N-1][1][1] - dp[N-1][1][0] + 1, 0)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
mG = [tuple(map(int, input().split())) for _ in range(N)]

mG.sort(key=lambda x: x[1], reverse=True)
mG.sort(key=lambda x: x[0])

# print(mG)###

vA1 = []
vL1 = []
vR1 = []
L = -1
R = 10**9 + 1

for l,r in mG[:-1]:
    L = max(L, l)
    R = min(R, r)
    vL1.append(L)
    vR1.append(R)
    vA1.append(R-L+1)

# print(vA1)###

vA2 = []
vL2 = []
vR2 = []
L = -1
R = 10**9 + 1

for l,r in mG[:0:-1]:
    L = max(L, l)
    R = min(R, r)
    vL2.append(L)
    vR2.append(R)
    vA2.append(R-L+1)

# print(vA2)###

M1 = max(a+b for a,b in zip(vA1, vA2[::-1]))

# pick max1
# and all others to 2
k = 0
idm = -1
for i,(l,r) in enumerate(mG):
    d = r-l+1
    if d > k:
        k = d
        idm = i
    
L = -1
R = 10**9 + 1

for i,(l,r) in enumerate(mG):
    if i==idm:
      continue
    L = max(L, l)
    R = min(R, r)

M2 = k + max(0, R-L+1)

print(max(M1,M2))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()

def resolve():
    n=int(input())
    I=[tuple(map(int,input().split())) for _ in range(n)]
    I.sort(lambda x:x[1])
    forL=[0]*n
    forL[0]=I[0][0]
    backL=[0]*n
    backL[-1]=I[-1][0]
    for i in range(n-1):
        forL[i+1]=max(forL[i],I[i+1][0])
        backL[-i-2]=max(backL[-i-1],I[-i-2][0])

    def calc1(i): # i番目で分けるやり方
        score=0
        score+=max(I[0][1]-forL[i-1]+1,0)
        score+=max(I[i][1]-backL[i]+1,0)
        return score
    ans1=max(calc1(i) for i in range(1,n))

    def calc2(i): # iつだけ別のやり方
        score=I[i][1]-I[i][0]+1
        if(0<i<n-1):
            score+=max(I[0][1]-max(forL[i-1],backL[i+1])+1,0)
        elif(i==0):
            score+=max(I[1][1]-max(forL[i-1],backL[i+1])+1,0)
        else:
            score+=max(I[0][1]-forL[i-1]+1,0)
        return score
    ans2=max(calc2(i) for i in range(n))

    print(max(ans1,ans2))
resolve()

Submission status: Accepted

Solution code:
from operator import itemgetter
N = int(input())
LR = []
for _ in range(N):
    l, r = map(int, input().split())
    LR.append([l, r+1])
ans = 0
for l, r in LR:
    ans = max(ans, r-l)
LR.sort(key=itemgetter(1))

# 区間スケジューリングの解が 3 以上のとき、
# 2 回とも楽しさが 1 以上になることはないので、
# 最も長い区間の幅がそのまま答えになる

# 解が 2 のときは、2 回とも楽しさが 1 以上になる場合も存在する
# これは、重ならない 2 つの区間を取り出して、
# 他の区間がそのどちらと一緒になるか考えれば良い
# 考えると、ある区間が別の区間を完全に被覆する場合、
# それらは必ず同じグループに含まれることがわかるので、
# 被覆する側の区間（大きい方）は無視できる
# 無視すると、区間の集合が半返し縫いの裏側みたいになるので
# 順に並べてどちらと一緒になるかの境目を全探索すれば良い

# 解が 1 のときは、全ての区間に共通する区間があるので、
# この区間の中の人を除外して考えると、
# 解が 2 の場合に帰着できる

sch = 0
rr = 0
for l, r in LR:
    if l >= rr:
        rr = r
        sch += 1
if sch >= 3:
    print(ans)
    exit()

mid_range = 0
if sch == 1:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    mid_range = mid_r - mid_l  # この値で補正すると区間スケジューリングの解が 2 のときと同じように解ける
    for i in range(N):
        LR[i][1] -= mid_range
    ans += mid_range

# 完全に被覆している区間は狭い方だけ残す
LR_ = []
pl = 0
for l, r in LR:
    if pl < l:
        LR_.append([l, r])
        pl = l
LR = LR_
if len(LR) == 1:
    print(ans)
    exit()

Ll, Lr = LR[0]
Rl, Rr = LR[-1][0], LR[1][1]
ans2 = max(Rr-Rl, 0) + Lr-Ll
for i, (l, r) in enumerate(LR[1:-1], 1):
    Ll = l
    Rr = LR[i+1][1]
    ans2 = max(ans2, max(Rr-Rl, 0) + max(Lr-Ll, 0))
ans2 += mid_range * 2
print(max(ans, ans2))

Submission status: Accepted

Solution code:
from operator import itemgetter
import sys
input = sys.stdin.readline
N = int(input())
LR = []
for _ in range(N):
    l, r = map(int, input().split())
    LR.append([l, r+1])
ans = 0
for l, r in LR:
    ans = max(ans, r-l)

LR.sort(key=itemgetter(1))

# 区間スケジューリング
sch = 0
rr = 0
for l, r in LR:
    if l >= rr:
        rr = r
        sch += 1
if sch >= 3:
    print(ans)
    exit()

mid_range = 0
if sch == 1:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    mid_range = mid_r - mid_l
    for i in range(N):
        LR[i][1] -= mid_range
    ans += mid_range

# 完全に被覆している区間は狭い方だけ残す
LR_ = []
pl = 0
for l, r in LR:
    if pl >= l:
        pass
    else:
        LR_.append([l, r])
        pl = l
LR = LR_
if len(LR) == 1:
    print(ans)
    exit()

Ll, Lr = LR[0]
Rl, Rr = LR[-1][0], LR[1][1]
ans2 = max(Rr-Rl, 0) + Lr-Ll
for i, (l, r) in enumerate(LR[1:-1], 1):
    Ll = l
    Rr = LR[i+1][1]
    ans2 = max(ans2, max(Rr-Rl, 0) + max(Lr-Ll, 0))
ans2 += mid_range * 2
print(max(ans, ans2))