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:
import itertools
import math
import os
import sys
from collections import defaultdict
from operator import itemgetter

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


class SparseTable:
    """
    構築 O(NlogN)、クエリ O(1)
    """

    def __init__(self, values, fn):
        """
        :param list values:
        :param callable fn: 結合則を満たす冪等な関数。min、max など。add はだめ
        """
        self._values = values
        self._fn = fn

        # SparseTable を構築
        # self._table[i][p]: [i, i+2^p) に fn を適用した結果の値のインデックス
        self._table = self._build(values, fn)

        # self._msb[i]: 最上位ビット; どの p を見るべきか
        self._msb = [0] * (len(values) + 1)
        for i in range(2, len(values) + 1):
            self._msb[i] = self._msb[i >> 1] + 1

    @staticmethod
    def _build(values, fn):
        # AtCoder の PyPy 2.4.0 では math.log2 が使えない
        size = int(math.log(len(values), 2)) + 1

        st = [[0] * size for _ in range(len(values))]
        for i in range(len(values)):
            st[i][0] = i
        for p in range(1, size):
            for i in range(len(values)):
                q = min(i + (1 << (p - 1)), len(values) - 1)
                l = st[i][p - 1]
                r = st[q][p - 1]
                if values[l] == fn(values[l], values[r]):
                    st[i][p] = l
                else:
                    st[i][p] = r
        return st

    def get(self, a, b):
        """
        半開区間 [a, b) に fn を適用した結果
        :param int a:
        :param int b:
        """
        if b <= a:
            return None
        p = self._msb[b - a]
        return self._fn(
            self._values[self._table[a][p]],
            self._values[self._table[b - (1 << p)][p]]
        )


N = int(sys.stdin.readline())
LR = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]


def calc_score(lr):
    ma = IINF
    mi = 0
    for l, r in lr:
        ma = min(ma, r)
        mi = max(mi, l)
    return max(0, ma - mi + 1)


def test(N, LR):
    import numpy as np
    LR = np.array(LR, dtype=int)
    ret = 0
    counts = defaultdict(int)
    for choice in itertools.product([True, False], repeat=N):
        if sum(choice) in [N, 0]:
            continue
        choice = np.array(choice)
        score = calc_score(LR[choice]) + calc_score(LR[~choice])
        if score >= ret:
            counts[score] = max(counts[score], sum(choice))
        ret = max(score, ret)
        # print(score, choice)
    # print(ret, counts[ret])
    return ret


def argsort(li, key=None, reverse=False):
    return [i for _, i in sorted([(a, i) for i, a in enumerate(li)], key=(lambda t: key(t[0])) if key else None, reverse=reverse)]


def solve():
    L, R = zip(*LR)
    L = list(L)
    R = list(R)
    if N == 2:
        ans = (R - L + 1).sum()
        print(ans)
        exit()

    # minR と minL のやつを同じグループにするとき、一番幅が広いのを他のグループにするのが最適。
    diff = [r - l for r, l in zip(R, L)]
    order = argsort(diff)
    L = [L[o] for o in order]
    R = [R[o] for o in order]
    diff.sort()
    li = L.index(max(L))
    ri = R.index(min(R))

    g1i = N - 1
    while g1i in [li, ri]:
        g1i -= 1
    g1 = diff[g1i] + 1
    g2 = max(0, R[ri] - L[li] + 1)
    ans1 = g1 + g2

    # minR と minL のやつを違うグループにするとき、どこで区切るかを全探索。
    LR.sort()
    L, R = zip(*LR)
    rsp = SparseTable(R, min)
    ans2 = 0
    for sep in range(1, N):
        max_l = L[sep - 1]
        min_r = rsp.get(0, sep)
        s1 = max(0, min_r - max_l + 1)
        max_l = L[-1]
        min_r = rsp.get(sep, N)
        s2 = max(0, min_r - max_l + 1)
        score = s1 + s2
        ans2 = max(score, ans2)

    LR.sort(key=itemgetter(1))
    L, R = zip(*LR)
    lsp = SparseTable(L, max)
    for sep in range(1, N):
        max_l = lsp.get(0, sep)
        min_r = R[0]
        s1 = max(0, min_r - max_l + 1)
        max_l = lsp.get(sep, N)
        min_r = R[sep]
        s2 = max(0, min_r - max_l + 1)
        score = s1 + s2
        ans2 = max(score, ans2)

    return max(ans1, ans2)


print(solve())
# assert test(N, LR) == solve()

Submission status: Runtime Error

Solution code:
import sys


def length(L1, L2, R1, R2):
    L = max(L1, L2)
    R = min(R1, R2)

    return R - L + 1


def leng(L, R):
    return R - L + 1


N = int(input())
L = [0] * N
R = [0] * N
Max_length = 0
Max = 0
Max_i_j = []
for i in range(N):
    L[i], R[i] = map(int, input().split())
    if Max < R[i] - L[i] + 1:
        Max = R[i] - L[i] + 1
        Max_i_j.append(i)

for j in range(len(Max_i_j)):

    Max_i = Max_i_j[j]

    Min = 10 ** 9
    Min_i = 0

    for i in range(N):
        if Min > (min(R[Max_i], R[i]) - max(L[Max_i], L[i])):
            Min = min(R[Max_i], R[i]) - max(L[Max_i], L[i])
            Min_i = i

    left = [L[Max_i], R[Max_i]]
    right = [L[Min_i], R[Min_i]]

    for i in range(N):
        if length(L[i], left[0], R[i], left[1]) + leng(right[0], right[1]) > leng(left[0], left[1]) + length(L[i],
                                                                                                             right[0],
                                                                                                             R[i],
                                                                                                             right[1]):
            left[0] = max(left[0], L[i])
            left[1] = min(left[1], R[i])

        else:
            right[0] = max(right[0], L[i])
            right[1] = min(right[1], R[i])

        if Max > leng(left[0], left[1]) + leng(right[0], right[1]):
            break

    if Max_length < leng(left[0], left[1]) + leng(right[0], right[1]):
        Max_length = leng(left[0], left[1]) + leng(right[0], right[1])

print(max(Max_length,max))

Submission status: Runtime Error

Solution code:
N = int(input())

info = [0] * N

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

info.sort()

x = info[-1][1]
stay = [1] * N

for i in range(2,N+1):
    if info[-i][1] < x:
        x = info[-i][1]
    else:
        stay[-i] = 0

info_ = []

for i in range(N):
    if stay[i] == 1:
        info_.append(info[i])

if len(info_) >= 2:
    length = [0] * len(info_)

    for i in range(len(info_)):
        length[i] = info_[i][1] - info_[i][0] + 1

    can = [max(length)]

    for i in range(len(info_)-1):
        can.append(max(0,info_[0][1] - info_[i][0] + 1) + max(0,info_[i+1][1] - info_[N-1][0] + 1))

    if len(info_) >= 2:
        print(max(can))

else:
    length = [0] * N

    for i in range(N):
        length[i] = info[i][1] - info[i][0] + 1
    
    length_ = info_[0][1] - info_[0][0] + 1

    print(length_ + max(length))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Nov  3 14:57:33 2019

@author: Tomomasa Takahashi
"""
def overlap(l):
    start = max(l[0][0],l[1][0])
    end = min(l[0][1],l[1][1])
    if start>end:
        return [0,-1]
    else:
        return [start,end]

def solve(Q):
    if len(Q)==2:
        fan = (Q[0][1]-Q[0][0]+1)+(Q[1][1]-Q[1][0]+1)
        contestant = Q
    else:
        new=Q[-1]
        fan_s, contestant_s = solve(Q[:-1])
        over = overlap(contestant_s)
        # separate
        fan_1 = (new[1]-new[0]+1)+(over[1]-over[0]+1)
        cont_1 = [new,over]
        #joint 1
        over2 = overlap([new, contestant_s[0]])
        fan_2 = (over2[1]-over2[0]+1)+(contestant_s[1][1]-contestant_s[1][0]+1)
        cont_2 = [over2,contestant_s[1]]
        #joint 2
        over3 = overlap([new, contestant_s[1]])
        fan_3 = (over3[1]-over3[0]+1)+(contestant_s[0][1]-contestant_s[0][0]+1)
        cont_3 = [over3,contestant_s[0]]
        if fan_1 > fan_2 and fan_1 > fan_3:
            fan = fan_1
            contestant = cont_1
        elif fan_2>fan_3:
            fan = fan_2
            contestant = cont_2
        else:
            fan = fan_3
            contestant = cont_3
    return fan, contestant

N = int(input())
Q=[]
for i in range(N):
    l, r = map(int, input().split())
    Q.append([l,r])

fan, contestant = solve(Q)
print(fan)

Submission status: Runtime Error

Solution code:
n = int(input())
raw = []
for _ in range(n):
  raw.append(list(map(int,input().split())))
raw.sort(key= lambda x: x[1])
EF = []
for i in range(n):
  EF.append(raw[i][1])
SL1 = [raw[0][0]]
for i in range(1,n):
  SL1.append(max(SL1[-1],raw[i][0]))
SL2 = [raw[-1][0]]
for i in range(1,n):
  SL2.append(max(SL2[-1],raw[n-i-1][0]))
SL2.reverse()
#print(EF)
#print(SL1)
#print(SL2)
can = []
for i in range(n-1):
  if EF[0] - SL1[i] + 1 > 0 and EF[i+1] - SL2[i+1] + 1 > 0:
    tmp = (EF[0]-SL1[i]+1) + (EF[i+1]-SL2[i+1]+1)
    can.append(tmp)
#print(can)
print(max(can))

Submission status: Runtime Error

Solution code:
n=int(input())
l=[]
for i in range(n):
    l.append(list(map(int,input().split())))
l=sorted(l,key=lambda x: x[0]-x[1])
ans1=l[1]-l[0]+1
lm=-1
rm=10**10
for i in range(1,n):
    lm=max(lm,l[i][0])
    rm=min(rm,l[i][1])
ans1+=max(0,rm-lm+1)

Submission status: Runtime Error

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

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

mR = float("inf")
ML = -float("inf")
indmR = 0
indML = 0
lenmR = 0
lenML = 0
for i in range(n):
    if mR > A[i][1] or (mR == A[i][1] and lenmR >= A[i][1]-A[i][0]+1):
        lenmR = A[i][1]-A[i][0]+1
        indmR = i
        mR = A[i][1]
    if ML < A[i][0] or (ML == A[i][0] and lenML > A[i][1]-A[i][0]+1):
        lenML = A[i][1]-A[i][0]+1
        indML = i
        ML = A[i][0]

ans = 0
lenmax2 = 0
for i in range(n):
    if i != indML and i != indmR:
        lenmax2 = max(lenmax2, A[i][1]-A[i][0]+1)

ans = max(0, mR-ML+1) + lenmax2
# print("ans",ans)

if indML != indmR:
    
    aa =[[ML, A[indML][1]], [A[indmR][0], mR]]
    aa_h = [[j for j in i] for i in aa]
    A.pop(indML)
    A.pop(indmR)
    # print(A)
    # print(aa)
    
    l = 0
    r = aa[1][1]-aa[1][0]+aa[0][1]-aa[0][0]+2
    m = (l+r)//2
    while r-l>1:
        aa = [[j for j in i] for i in aa_h]
        for i in range(len(A)):
            # print(aa_h[0][1] , A[i][1] , m)
            if aa_h[0][1] - A[i][1] > m:
                aa[1][0] = max(aa[1][0], A[i][0])
            else:
                aa[0][1] = min(aa[0][1], A[i][1])
        # print("aa",aa,m)
        if aa_h[0][1] - aa[0][1] + aa[1][0] - aa_h[1][0] > m:
            l = m
        else:
            r = m
        m = (l+r)//2

    # print("ans", l+1)
    aa = [[j for j in i] for i in aa_h]
    ans = max(ans, aa[1][1]-aa[1][0]+aa[0][1]-aa[0][0]+2-(l+1))
print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
l=[]
for i in range(n):
    l.append(list(map(int,input().split())))
l=sorted(l,key=lambda x: x[0]-x[1])
ans1=l[1]-l[0]+1
lm=-1
rm=10**10
for i in range(1,n):
    lm=max(l[i][0])
    rm=min(l[i][1])
ans1+=max(0,rm-lm+1)

Submission status: Runtime Error

Solution code:
n=int(input())
l=[]
for i in range(n):
    l.append(list(map(int,input().split()))))
l=sorted(l,key=lambda x:x[1]-x[0])
print(l[-1][1]-l[-1][0])