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:
from fractions import gcd
from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
import sys
from bisect import *
import itertools
import copy
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7


def main():
   n = int(input())
   lr = [list(map(int, input().split())) for i in range(n)]
   lr = sorted(lr, key=lambda x: x[0])
   ans1 = []
   ans = lr[0][1] - lr[0][0] + 1
   ans1.append(ans)
   l,r = lr[0][0],lr[0][1]
   for i in range(1, n):
       ans = max(ans , lr[i][1] - lr[i][0] + 1)
       if l < lr[i][0]:
           l = lr[i][0]
       if r > lr[i][1]:
            r = lr[i][1]
       ans1.append(r - l + 1)

   ans2 = []
   ans = lr[n-1][1] - lr[n-1][0] + 1
   ans2.append(ans)
   l,r = lr[n-1][0],lr[n-1][1]
   for i in range(n-2,-1,-1):
       if r > lr[i][1]:
            r = lr[i][1]
       ans2.append(r - l + 1)
   #print(ans1,ans2)
   ans = 0
   for i in range(n-1):
       ans = max(ans , ans1[i] + ans2[n-i-2] )
   #print(ans)
   tans = ans

   lr = sorted(lr, key=lambda x: x[1],reverse=True)
   ans1 = []
   ans = lr[0][1] - lr[0][0] + 1
   ans1.append(ans)
   l, r = lr[0][0], lr[0][1]
   for i in range(1, n):
       ans = max(ans, lr[i][1] - lr[i][0] + 1)
       if l < lr[i][0]:
           l = lr[i][0]
       if r > lr[i][1]:
            r = lr[i][1]
       ans1.append(r - l + 1)

   ans2 = []
   ans = lr[n-1][1] - lr[n-1][0] + 1
   ans2.append(ans)
   l, r = lr[n-1][0], lr[n-1][1]
   for i in range(n - 2, -1, -1):
       if l < lr[i][0]:
           l = lr[i][0]
       if r > lr[i][1]:
            r = lr[i][1]
       ans2.append(r - l + 1)
   #print(ans1,ans2)
   ans = tans
   for i in range(n-1):
       ans = max(ans, ans1[i] + ans2[n - i - 2])
   print(ans)
   
             
        
        
            

    
   


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
maxlen = int(0)
N = I()
LR =[[] for _ in range(N)]
for i in range(N):
    LR[i] = LI()
    C = LR[i][1] - LR[i][0]
    if C>maxlen:
        maxlen = C

LR.sort()
rightend = LR[0][1]
leftend  = LR[N-1][0]

live1 = [[] for _ in range(N)]
live2 = [[] for _ in range(N)]
live1[0] = LR[0]
live2[N-1] = LR[N-1]
#print(rightend)
#print(leftend)

cur1 = -1; cur2 = -1
for i in range(1,N):
    if live1[i-1][1]>LR[i][1]:
        rightend = LR[i][1]
    if rightend<LR[i][0]:
        cur1 = i-1
        break
    live1[i] = [max(live1[i-1][0],LR[i][0]),min(live1[i-1][1],LR[i][1])]

for i in range(N-2,-1,-1):
    if live2[i+1][1]>LR[i][0]:
        leftend = LR[i][0]
    if leftend>LR[i][1]:
        cur2 = i+1
        break
    live2[i] = [max(live2[i+1][0],LR[i][0]),min(live2[i+1][1],LR[i][1])]
#print(cur1,cur2)
#print(live1)
#print(live2)

if cur1==-1:
    cur1=N-2
if cur2==-1:
    cur2=1
ansC = [0]*N
for i in range(cur2,cur1+2):
    ansC[i] = (live1[i-1][1]-live1[i-1][0]+1) + (live2[i][1]-live2[i][0]+1)

ans = max(max(ansC),maxlen+1)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = [[]]*N
max_n = 0
min_n = 10**9
for i in range(N):
    LR[i] = list(map(int, input().split()))
    min_n = min(min_n, LR[i][0])
    max_n = max(max_n, LR[i][1])

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


set1 = [LR[0][0], LR[0][1]]
set2 = [LR[1][0], LR[1][1]]

for i in range(2, N):
    if max((min(set1[1], LR[i][1]) - max(set1[0], LR[i][0]))+1, 0)+(set2[1]-set2[0]+1) >= max((min(set2[1], LR[i][1]) - max(set2[0], LR[i][0])+1), 0) + (set1[1]-set1[0]+1):
        set1 = [max(set1[0], LR[i][0]), min(set1[1], LR[i][1])]
    else:
        set2 = [max(set2[0], LR[i][0]), min(set2[1], LR[i][1])]

ans1 = set1[1] - set1[0]+1 + set2[1]-set2[0]+1


print(ans1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- Coding: utf-8 -*-

import sys
import copy


input = sys.stdin.readline


def main():
    N = int(input())
    q = [[int(i) for i in input().split()] for _ in range(N)]

    # f = q.pop()
    # s = [0, 10**9]
    # tmp = float('inf')
    # for a in q:
    #     n = cal(a, f)
    #     if n < tmp:
    #         s = copy.copy(a)
    #         tmp = n

    q.sort(key=lambda x: x[0], reverse=True)
    f = q.pop()
    q.sort(key=lambda x: x[1])
    s = q.pop()
    for a in q:
        ln = cal(f, [0, 10**9])
        lm = cal(s, [0, 10**9])
        n = cal(f, a)
        m = cal(s, a)
        if n+lm > ln+m:
            f[0] = max(f[0], a[0])
            f[1] = min(f[1], a[1])
        elif n+lm == ln+m:
            if lm > ln:
                f[0] = max(f[0], a[0])
                f[1] = min(f[1], a[1])
            else:
                s[0] = max(s[0], a[0])
                s[1] = min(s[1], a[1])

        else:
            s[0] = max(s[0], a[0])
            s[1] = min(s[1], a[1])
    print(max(f[1]-f[0]+1, 0)+max(s[1]-s[0]+1, 0))


def cal(a1, a2):
    return min(a1[1], a2[1])-max(a1[0], a2[0])+1


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
P = 10**9
N = int(input())
LR = [ inpl() for _ in range(N) ]
LR.sort()

K = 0
mlist = []
for i in range(N):
    l, r = LR[i]
    k = r -l + 1
    if k == K:
        mlist.append(i)
    elif k > K:
        mlist = [i]
        K = k
U = []
r = P
for i in range(N):
    l = LR[i][0]
    r = min(r, LR[i][1])
    U.append((l,r))
D = [None]*N
l = LR[-1][0]
for i in range(N):
    r = min(r, LR[N-1-i][1])
    D[N-1-i] = (l,r)

ans = K
for m in mlist:
    if m == 0:
        score = K + max(0, D[1][1]-D[1][0]+1)
    elif m == N-1:
        score = K + max(0, U[-1][1]-U[-1][0]+1)
    else:
        score = K + max(0, min(U[m-1][1],D[m+1][1]) - D[m+1][0] + 1)
    if score > ans:
        ans = score

LR2 = [LR[0]]
for i in range(1,N):
    if LR2[-1][1] < LR[i][1]:
        LR2.append(LR[i])
    else:
        LR2[-1] = LR[i]
M = len(LR2)
if M < 2:
    print(ans)
    exit()

R1 = LR2[0][1]
L2 = LR2[-1][0]
for i in range(M-1):
    L1 = LR2[i][0]
    R2 = LR2[i+1][1]
    score = max(0, R1-L1+1) + max(0, R2-L2+1)
    if score > ans:
        ans = score

print(ans)

Submission status: Wrong Answer

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

ls.sort(key = lambda x:x[0])
INF = 1001001001001001001
min_ls1 = [INF] * n
min_ls1[0] = ls[0][1]
for i in range(1, n):
    min_ls1[i] = min(min_ls1[i-1], ls[i][1])

min_ls2 = [INF] * n
min_ls2[-1] = ls[-1][1]
for i in reversed(range(n-1)):
    min_ls2[i] = min(min_ls2[i+1], ls[i][1])

ans_ls = [0] * (n-1)

for i in range(n-1):
    p1 = ls[i][0]
    p2 = min_ls1[i]
    p3 = ls[-1][0]
    p4 = min_ls2[i+1]
    ans_ls[i] += max(p2 - p1 + 1, 0) + max(p4 - p3 + 1, 0)

print(max(ans_ls))

Submission status: Wrong Answer

Solution code:
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
maxlen = int(0)
N = I()
LR =[[] for _ in range(N)]
for i in range(N):
    LR[i] = LI()
    C = LR[i][1] - LR[i][0]
    if C>maxlen:
        maxlen = C

LR.sort()
rightend = LR[0][1]
leftend  = LR[N-1][0]

live1 = [[] for _ in range(N)]
live2 = [[] for _ in range(N)]
live1[0] = LR[0]
live2[N-1] = LR[N-1]
#print(rightend)
#print(leftend)

cur1 = -1; cur2 = -1
for i in range(1,N):
    if rightend<LR[i][0]:
        cur1 = i-1
        break
    live1[i] = [max(live1[i-1][0],LR[i][0]),min(live1[i-1][1],LR[i][1])]
    if live1[i-1][1]>LR[i][1]:
        rightend = LR[i][1]

for i in range(N-2,-1,-1):
    if leftend>LR[i][1]:
        cur2 = i+1
        break
    live2[i] = [max(live2[i+1][0],LR[i][0]),min(live2[i+1][1],LR[i][1])]
    if live2[i+1][1]>LR[i][0]:
        leftend = LR[i][0]
#print(cur1,cur2)
#print(live1)
#print(live2)

if cur1==-1:
    cur1=N-2
if cur2==-1:
    cur2=1
ansC = [0]*N
for i in range(cur2,cur1+2):
    ansC[i] = (live1[i-1][1]-live1[i-1][0]+1) + (live2[i][1]-live2[i][0]+1)

ans = max(max(ansC),maxlen+1)

print(ans)

Submission status: Wrong Answer

Solution code:
# import sys
#
# sys.setrecursionlimit(10 ** 7)
#
# input = sys.stdin.readline
# rstrip()

# int(input())
# map(int, input().split())

# 2回のコンテストに問題を分ける、一回だけ出題
# すべての問題を解く参加者の人数の和を最大化


def solve(n, e):
    from operator import itemgetter
    e.sort(key=itemgetter(2, 0))
    # print(e)

    ll, lr, _ = e[-1]  # 最大
    rl, rr, _ = e[0]  # 最小

    for i in range(1, n - 2):
        l, r, _ = e[i]
        rl = max(rl, l)
        rr = min(rr, r)

    l, r, _ = e[n - 2]
    sr = max(0, (rr - rl + 1))
    mr = max(0, (min(rr, r) - max(rl, l) + 1))
    diff_r = sr - mr

    sl = max(0, (lr - ll + 1))
    ml = max(0, (min(lr, r) - max(ll, l) + 1))
    diff_l = sl - ml

    if diff_r < diff_l:
        rl = max(rl, l)
        rr = min(rr, r)
    else:
        ll = max(ll, l)
        lr = min(lr, r)

    print(max(0, (lr - ll + 1)) + max(0, (rr - rl + 1)))
    # print(ll, lr, rl, rr)


if __name__ == '__main__':
    n = int(input())
    e = []
    for _ in range(n):
        lr = tuple(int(x) - 1 for x in input().split())
        lr = lr + (lr[1] - lr[0] + 1,)
        e.append(lr)
    solve(n, e)

Submission status: Wrong Answer

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

Solution code:
import sys
from operator import itemgetter
import numpy as np
read = sys.stdin.read


def main():
    N, *LR = map(int, read().split())

    LR = list(zip(*[iter(LR)] * 2))
    LR.sort(key=itemgetter(0))

    left = 0
    right = 10 ** 19
    day1 = [0] * N

    for i in range(N - 1):
        if left < LR[i][0]:
            left = LR[i][0]
        if right > LR[i][1]:
            right = LR[i][1]
        day1[i] = right - left + 1

    day2 = [0] * N
    left = 0
    right = 10 ** 19
    for i in range(N - 1, 0, -1):
        if left < LR[i][0]:
            left = LR[i][0]
        if right > LR[i][1]:
            right = LR[i][1]
        day2[i] = right - left + 1

    day1 = np.array([0] + day1)
    day2 = np.array(day2 + [0])
    answer1 = day1 + day2

    LR.sort(key=itemgetter(1))

    left = 0
    right = 10 ** 19
    day1 = [0] * N

    for i in range(N - 1):
        if left < LR[i][0]:
            left = LR[i][0]
        if right > LR[i][1]:
            right = LR[i][1]
        day1[i] = right - left + 1

    day2 = [0] * N
    left = 0
    right = 10 ** 19
    for i in range(N - 1, 0, -1):
        if left < LR[i][0]:
            left = LR[i][0]
        if right > LR[i][1]:
            right = LR[i][1]
        day2[i] = right - left + 1

    day1 = np.array([0] + day1)
    day2 = np.array(day2 + [0])
    answer2 = day1 + day2

    print(max(answer1.max(), answer2.max()))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = []
for i in range(N):
    L, R = map(int, input().split())
    LR.append([L, R])

LR.sort(key=lambda x:x[0])

Lmin = LR[0][0]
Lmax = LR[0][1]

Rmin = LR[-1][0]
Rmax = LR[-1][1]

for a in LR[1:-1]:
    l = Lmin - a[0]
    l += min(0, a[1] - Lmax)

    r = min(0, a[1] - Rmax)

    if l >= r:
        Lmin = a[0]
        Lmax = min(Lmax, a[1])
    
    else:
        Rmax = min(a[1], Rmax)


lcnt = max(0, Lmax - Lmin + 1)
rcnt = max(0, Rmax - Rmin + 1)
print(lcnt + rcnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = [list(map(int, input().split())) for _ in range(N)]
lr.sort()
lr2 = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    lr2.append(lr[i])
R = lr2[-1][1]
lr1 = [lr2[-1]]
for l, r in lr2[-2::-1]:
    if R<r:
        continue
    lr1.append([l, r])
    R = r
lr1 = list(reversed(lr1))
ans1 = [0]
ans2 = [0]
R = lr1[0][1]
for l, r in lr1:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr1[-1][0]
for l, r in lr1[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
m = 0
L, R = [], []
index = []
for i in range(N):
    l, r = lr[i]
    L.append(l)
    R.append(r)
    if m<r-l:
        index = [i]
        m = r-l
    elif m == r-l:
        index.append(i)
L.sort()
R.sort()
for i in index:
    l, r = lr[i]
    if L[-1] == l:
        l  =  L[-2]
    else:
        l = L[-1]
    if R[0] == r:
        r = R[1]
    else:
        r = R[0]
ans = m+1+r-l+1
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

Solution code:
def f(li, new):
    l1, r1, d1 = li[0]
    l2, r2, d2 = li[1]
    l3, r3, d3 = new
    l = [l1, l2, l3]
    r = [r1, r2, r3]
    d = [d1, d2, d3]

    mn = float("inf")
    for i in range(3):
        new_l = max(l[i-1], l[i-2])
        new_r = min(r[i-1], r[i-2])
        new_d = max(0, new_r - new_l + 1)
        d_diff = d[i-1] + d[i-2] - new_d
        if d_diff < mn:
            mn = d_diff
            left = i
            new = [new_l, new_r, new_d]

    if new[0] > new[1]:
        new[0] = -1
        new[1] = -1
    ret = [[l[left], r[left], d[left]], new]
    ret.sort(reverse=True, key=lambda x: x[2])
    return ret


def main():
    n = int(input())
    lr = [list(map(int, input().split())) for _ in range(n)]

    lrd = []
    for l, r in lr:
        lrd.append([l, r, r - l + 1])

    lrd.sort(reverse=True, key=lambda x: x[2])

    ans = [lrd[0], lrd[1]]

    for li in lrd[2:]:
        ans = f(ans, li)

    print(ans[0][2] + ans[1][2])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

ltor = {}
rtol = {}
ans = 0
for i,(l,r) in enumerate(LR):
    ans = max(ans, r-l+1)
    if l in ltor:
        ltor[l] = min(r, ltor[l])
    else:
        ltor[l] = r
    if r in rtol:
        rtol[r] = max(l, rtol[r])
    else:
        rtol[r] = l
ls = list(ltor.keys())
ls.sort()
rs = list(rtol.keys())
rs.sort(reverse=True)

ll_ans = [0]
minr = 10**9+10
for l in ls:
    r = ltor[l]
    minr = min(r, minr)
    ll_ans.append(max(0, minr - l + 1))

lr_ans = [0]
maxl = 0
minr = 10**9+10
for l in reversed(ls):
    r = ltor[l]
    minr = min(r, minr)
    maxl = max(l, maxl)
    lr_ans.append(max(0, minr - maxl + 1))
lr_ans.reverse()

rr_ans = [0]
maxl = -10
for r in rs:
    l = rtol[r]
    maxl = max(l, maxl)
    rr_ans.append(max(0, r - maxl + 1))

rl_ans = [0]
minr = 10**9
maxl = -10
for r in reversed(rs):
    l = rtol[r]
    maxl = max(l, maxl)
    minr = min(r, minr)
    rl_ans.append(max(0, minr - maxl + 1))
rl_ans.reverse()

for l,r in list(zip(ll_ans, lr_ans))[1:-1]:
    ans = max(ans, l+r)
for l,r in list(zip(rl_ans, rr_ans))[1:-1]:
    ans = max(ans, l+r)

print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
Q=[]
Q1=[]
Q2=[]
for i in range(N):
  Q.append(list(map(int,input().split())))
Q.sort()
for i in Q:
  Q1.append(i[0])
  Q2.append(i[1])
ans=0

min1=Q2[0]
Q2n=Q2[0:]
Q2n.sort()
if min1==Q2n[0]:
  flag=1
else:
  flag=0

for i in range(N-1):
  tmp=max(0,min1-Q1[i]+1) + max(0,Q2n[flag]-Q1[-1]+1)
  if min1>Q2[i+1]:
    min1=Q2[i+1]
  if Q2n[flag]==Q2[i+1]:
    flag+=1
  #print(ans)
  if ans<tmp:
    ans=tmp
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = []
B = []
for i in range(N):
    L,R = map(int,input().split())
    A.append([L,R,i])
B = sorted(A)
C = sorted(A, key=lambda x: x[1])
l0,l1,m0,m1 = B[N-1][0],B[N-1][1],C[0][0],C[0][1]
I,J = B[N-1][2],C[0][2]
M = 0
if I == J:
    for i in range(N):
        a1,a0 = A[i][1],A[i][0]
        if M <= a1-a0:
            M = a1-a0
    ans = m1-l0 + M+2
else:
    for i in range(N):
        if i == I or i == J:
            continue
        a1,a0 = A[i][1],A[i][0]
        if M <= a1-a0:
            M = a1-a0
    ans1 = m1-l0 + M
    a,b = l1-l0,m1-m0
    for i in range(N):
        if i == I or i == J:
            continue
        a1,a0 = B[i][1],B[i][0]
        if min([l1,a1])-l0 + m1-m0>l1-l0 + m1-max([m0,a0]):
            l1 = min([l1,a1])
        else:
            m0 = max([m0,a0])
    ans2 = l1-l0+m1-m0
    ans = max([ans1+2,ans2+2,0])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
m=10**9
n = int(input())
bd = [[0,0] for _ in range(n)]
minr = 10**9+1
minrInd = -1
maxl = 0
maxlInd = -1
maxrange = 0
secmax = 0
thmax = 0
maxi = -1
seci = -1
thi = -1
for i in range(n):
    l, r = map(int, sys.stdin.readline().split())
    if l > maxl:
        maxl = l
        maxlInd = i
    if r < minr:
        minr = r
        minrInd = i
    if r-l > maxrange:
        thmax = secmax
        secmax = maxrange
        maxrange = r-l
        thi = seci
        seci = maxi
        maxi = i
    elif  r-l > secmax:
        thmax = secmax
        secmax = r-l
        thi = seci
        seci = i
    elif  r-l > thmax:
        thmax = r-l
        thi = i


    bd[i][0] = l
    bd[i][1] = r
if maxlInd == minrInd:
    print(max(0, minr - maxl + maxrange + 2 ))
    exit()
tmpmax = 0
if maxi != maxlInd:
    if maxi != minrInd:
        tmpmax = minr - maxl + maxrange + 2
    elif seci != maxlInd and seci != -1:
        tmpmax = minr - maxl + secmax + 2
    elif thi != -1:
        tmpmax = minr - maxl + thmax + 2
elif seci != minrInd and seci != -1:
    tmpmax = minr - maxl + secmax + 2
elif thi != -1:
    tmpmax = minr - maxl + thmax + 2

lb1 = bd[minrInd][0]
rb1 = bd[minrInd][1]
lb2 = bd[maxlInd][0]
rb2 = bd[maxlInd][1]
for i in range(n):
    if bd[i][0] <= lb1:
        continue
    elif bd[i][1] >= rb2:
        continue
    elif rb1 - bd[i][0] + rb2 - lb2 > rb1 - lb1 + bd[i][1] - lb2:
        lb1 = bd[i][0]
    else:
        rb2 = bd[i][1]

print(max(tmpmax, rb1 - lb1 + rb2 - lb2 + 2))

Submission status: Wrong Answer

Solution code:

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

Lsorted = sorted(sorted(LR,key=lambda x:x[1],reverse=True),key = lambda x: x[0],reverse=True)
Rsorted = sorted(sorted(LR,key=lambda x:x[0]),key = lambda x: x[1])

Lmax = Lsorted[0]
Rmin = Rsorted[0]
if Lmax[0]==Rmin[0] and Lmax[1]==Rmin[1]:
    LRdif = [LR[i][1]-LR[i][0]+1 for i in range(N)]
    LRdif.sort()
    print(Lmax[1]-Lmax[0]+1+LRdif[-1])
else:
#    M1 = Lmax[1]
#    M2 = Rmin[0]
#    for l,r in LR:
#        if r-Lmax[0] > Rmin[1]-l:
#            M1 = max(min(r,M1),Lmax[0]-1)
#        else:
#            M2 = min(max(l,M2),Rmin[1]+1)
#    print(M1-Lmax[0]+1 + Rmin[1]-M2+1)
    Rsorted = sorted(sorted(LR,key=lambda x:x[0]),key=lambda x:[1])
    maxL = Rmin[0]
    maxscore = 0
    for i in range(N):
        if Rsorted[i][2]!=Lmax[2]:
            maxL = max(Rsorted[i][0],maxL)
            nowminR = Rsorted[i+1][1]
            maxscore =max(maxscore, max(nowminR-Lmax[0]+1,0) + max(Rmin[1]-maxL+1,0))
        else:
            break
                
#    Lsorted = sorted(sorted(LR,key=lambda x:x[1],reverse=True),key=lambda x:[0],reverse=True)
#    minR = Lmax[1]
#    for i in range(1,N):
#        nowmaxL = min(Lsorted[i][0],Rmin[0])
#        maxscore =max(maxscore, max(minR-Lmax[0]+1,0) + max(Rmin[1]-nowmaxL+1,0))
#        minR = max(Lsorted[i][1],minR)

    print(maxscore)

Submission status: Wrong Answer

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]):
            print(Max)
            sys.exit()
    
    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_length)

Submission status: Wrong Answer

Solution code:
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


class SegmentTree():
    '''
    非再帰
    segment tree
    '''

    def __init__(self, n, func, init=float('inf')):
        '''
        n->配列の長さ
        func:func(a,b)->val,　func=minだとRMQになる
        木の高さhとすると,
        n:h-1までのノード数。h段目のノードにアクセスするために使う。
        data:ノード。
        parent:k->child k*2+1とk*2+2
        '''
        self.n = 2**(n-1).bit_length()
        self.init = init
        self.data = [init]*(2*self.n)
        self.func = func

    def set(self, k, v):
        '''
        あたいの初期化
        '''
        self.data[k+self.n-1] = v

    def build(self):
        '''
        setの後に一斉更新
        '''
        for k in reversed(range(self.n-1)):
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def update(self, k, a):
        '''
        list[k]=aに更新する。
        更新ぶんをrootまで更新
        '''
        k += self.n-1
        self.data[k] = a

        while k > 0:
            k = (k-1)//2
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def query(self, l, r):
        '''
        [l,r)のfuncを求める
        '''
        L = l+self.n
        R = r+self.n
        ret = self.init
        while L < R:
            if R & 1:
                R -= 1
                ret = self.func(ret, self.data[R-1])
            if L & 1:
                ret = self.func(ret, self.data[L-1])
                L += 1
            L >>= 1
            R >>= 1
        return ret


N = int(input())
L = [list(map(int, input().split())) for _ in range(N)]
L = sorted(L, key=lambda x: x[0])

Seg_L = SegmentTree(N, lambda a, b: max(a, b), init=0)
Seg_R = SegmentTree(N, lambda a, b: min(a, b), init=float('inf'))

for i, q in enumerate(L):
    l, r = q[0], q[1]
    Seg_L.set(i, l)
    Seg_R.set(i, r)
Seg_L.build()
Seg_R.build()
cand = []
for pivot in range(1, N):
    low_1, high_1 = Seg_L.query(0, pivot), Seg_R.query(0, pivot)
    low_2, high_2 = Seg_L.query(pivot, N), Seg_R.query(pivot, N)
    p1 = max(high_1-low_1, 0)
    p2 = max(high_2-low_2, 0)
    ans = p1+p2+2
    cand.append(ans)
ans1 = max(cand)

cand2 = []
for rem in range(N):
    rem_low = Seg_L.query(rem, rem+1)
    rem_high = Seg_R.query(rem, rem+1)
    use_low = max(Seg_L.query(0, rem), Seg_L.query(rem+1, N))
    use_high = min(Seg_R.query(0, rem), Seg_R.query(rem+1, N))
    p1 = max(rem_high-rem_low, 0)
    p2 = max(use_high-use_low, 0)
    ans = p1+p2+2
    cand2.append(ans)
ans2 = max(cand2)
print(max(ans1, ans2))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Mon Nov  4 01:34:42 2019

@author: miz18
"""


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

Lsorted = sorted(sorted(LR,key=lambda x:x[1],reverse=True),key = lambda x: x[0],reverse=True)
Rsorted = sorted(LR,key = lambda x: x[1])

Lmax = Lsorted[0]
Rmin = Rsorted[0]
if Lmax[0]==Rmin[0] and Lmax[1]==Rmin[1]:
    LRdif = [LR[i][1]-LR[i][0]+1 for i in range(N)]
    LRdif.sort()
    print(Lmax[1]-Lmax[0]+1+LRdif[-1])
else:
#    M1 = Lmax[1]
#    M2 = Rmin[0]
#    for l,r in LR:
#        if r-Lmax[0] > Rmin[1]-l:
#            M1 = max(min(r,M1),Lmax[0]-1)
#        else:
#            M2 = min(max(l,M2),Rmin[1]+1)
#    print(M1-Lmax[0]+1 + Rmin[1]-M2+1)
    Rsorted = sorted(sorted(LR,key=lambda x:x[0]),key=lambda x:[1])
    maxL = Rmin[0]
    maxscore = 0
    for i in range(N):
        if Rsorted[i][2]!=Lmax[2]:
            maxL = max(Rsorted[i][0],maxL)
            nowminR = Rsorted[i+1][1]
            maxscore =max(maxscore, max(nowminR-Lmax[0]+1,0) + max(Rmin[1]-maxL+1,0))
        else:
            break
                
#    Lsorted = sorted(sorted(LR,key=lambda x:x[1],reverse=True),key=lambda x:[0],reverse=True)
#    minR = Lmax[1]
#    for i in range(1,N):
#        nowmaxL = min(Lsorted[i][0],Rmin[0])
#        maxscore =max(maxscore, max(minR-Lmax[0]+1,0) + max(Rmin[1]-nowmaxL+1,0))
#        minR = max(Lsorted[i][1],minR)

    print(maxscore)

Submission status: Wrong Answer

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


def f(c1, c2):
    l, r = -1, -1
    l1, r1 = c1[0], c1[1]
    l2, r2 = c2[0], c2[1]
    if l1 <= l2 <= r1:
        l, r = l2, r1
    if l2 <= l1 <= r2:
        l, r = l1, r2
    if l2 <= l1 and r1 <= r2:
        l, r = l1, r1
    if l1 <= l2 and r2 <= r1:
        l, r = l2, r2
    n = r-l+1
    if l == -1 and r == -1:
        l, r = l1, r1
        n = 0
    return (l, r, n)


def main():
    N = int(input())
    LR = []
    for _ in range(N):
        l, r = map(int, input().split())
        LR.append((l, r, r-l+1))
    LR.sort(key=lambda x: x[2])
    c1 = LR[0]
    c2 = LR[-1]
#    print(LR, c1, c2)
    for i in range(1, len(LR)-1):
        x = LR[i]
        tmp1 = f(c1, x)
        tmp2 = f(c2, x)
        a = c1[2] + c2[2]
        if abs(a - (tmp1[2] + c2[2])) < abs(a - (c1[2] + tmp2[2])):
            c1 = tmp1
        else:
            c2 = tmp2
#        print("c1/c2", c1, c2)
    print(c1[2]+c2[2])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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[0][1]-l[0][0]+1
ans2=l[1][1]-l[1][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)
lm=-1
rm=10**10
for i in range(n):
    if i==1:
        continue
    lm=max(lm,l[i][0])
    rm=min(lm,l[i][1])
ans2+=max(0,rm-lm+1)
print(max(ans1,ans2))

Submission status: Wrong Answer

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]

    if indmR > indML:
        A.pop(indmR)
        A.pop(indML)
    else:
        A.pop(indML)
        A.pop(indmR)
    # print(A)
    # print(aa)
    
    l = -1
    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)