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:
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:
    alone = [0] * len(info_)

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

    can = [max(alone)]

    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_[-1][0] + 1))

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

Solution code:
import bisect, collections, heapq, sys
input = sys.stdin.readline

n = int(input())
problem_list = []
r = 10**9+1
p_list = []
for i in range(n):
    a, b = [ int(v) for v in input().split() ]
    p_list.append(a)
    p_list.append(b)
    problem_list.append([b, a])
problem_list.sort()
problem_list = [ [i[1],i[0]] for i in problem_list ]

p_list.sort()
problem_list = [ ( bisect.bisect_left(p_list,i[0]), bisect.bisect_left(p_list,i[1]) )  for i in problem_list ]

left_list = [ 0 for i in range(2*n) ]
right_list = [ 0 for i in range(2*n) ]
for a, b in problem_list:
    left_list[a] += 1
    right_list[b] += 1

ans = 0
la = problem_list[-1][0]
ra = None
lenr = len(right_list) 
for i in range(lenr):
    if right_list[i] > 0:
        ra = i
        break
lb, rb = -1, 10**6+1

for a, b in problem_list[:-1]:
    
    left_list[a] -= 1
    right_list[b] -= 1
    lb = max(lb,a)
    rb = min(rb,b)

    if left_list[la] == 0:
        for i in range(1,2**n):
            if left_list[la+i] != 0:
                la += i
                break
    if right_list[ra] == 0:
        for i in range(1,2**n):
            if right_list[ra+i] != 0:
                ra += i
                break

    ans = max(ans,(max(p_list[rb]-p_list[lb]+1,0)+max(p_list[ra]-p_list[la]+1,0)))

print(ans)

Submission status: Wrong Answer

Solution code:
# 一番長いLRが最低の楽しさ
# 一番長いLRと重なるのが一番少ないものはもう一つにする
# 一番長いLRが最低の楽しさ 一番長いLRが複数ある場合どうする？
# 一番長いLRと重なるのが一番少ないものはもう一つにする
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
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)
for i, (l, r) in enumerate(LR):
    if min(right_ma, r) - max(left_ma, l) < another:
        if r-l > another_length:
            another = min(right_ma, r) - max(left_ma, l)
            another_length = r-l+1
            i_an = i
            left_an = l
            right_an = r
point = ma + another_length
LR.pop(i_an)
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: Wrong Answer

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

iLR = [(i, Li, Ri) for i, (Li, Ri) in enumerate(LR)]
iLR_minR = sorted(iLR, key=lambda x: (x[2], -x[1]))
iLR_maxL = sorted(iLR, key=lambda x: (-x[1], x[2]))

def myeval(arg):
    if arg[0] != None:
        L_tmp, R_tmp = arg[0]
        score = max(0, R_tmp - L_tmp + 1)
    else:
        score = 0
    if arg[1] != None:
        L_tmp, R_tmp = arg[1]
        score += max(0, R_tmp - L_tmp + 1)
    else:
        score += 0
    return score

if iLR_minR[0][0] == iLR_maxL[0][0]:
    q = [(iLR_minR[0][0], iLR_maxL[-1][0]), (iLR_minR[-1][0], iLR_maxL[0][0])]
else:
    q = [(iLR_minR[0][0], iLR_maxL[0][0])]
    
ans = [None, None]
while len(q) > 0:
    i_L, i_R = q.pop()
    ans_tmp = [tuple(LR[i_L]), tuple(LR[i_R])]
    # print('#', ans_tmp)
    for i, (Li, Ri) in enumerate(LR):
        if i == i_L: continue
        if i == i_R: continue
        # print("##", ans_tmp, myeval(ans_tmp))
        # add left
        ans_l = list(ans_tmp)
        if ans_l[0] != None: L_tmp, R_tmp = ans_l[0]
        else: L_tmp, R_tmp = (0, 10 ** 9 + 7)
        ans_l[0] = (max(L_tmp, Li), min(R_tmp, Ri))
        score_l = myeval(ans_l)
        # print("###", ans_l, score_l)
        # add right
        ans_r = list(ans_tmp)
        if ans_r[1] != None: L_tmp, R_tmp = ans_r[1]
        else: L_tmp, R_tmp = (0, 10 ** 9 + 7)
        ans_r[1] = (max(L_tmp, Li), min(R_tmp, Ri))
        score_r = myeval(ans_r)
        # print("###", ans_r, score_r)
        # judge
        if score_l < score_r:
            ans_tmp = list(ans_r)
        else:
            ans_tmp = list(ans_l)
    #
    if myeval(ans) <= myeval(ans_tmp):
        ans = list(ans_tmp)

print(myeval(ans))

Submission status: Wrong Answer

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

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

mG.sort(key=lambda x: x[1])
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)###

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

print(max(M1, M2))

Submission status: Wrong Answer

Solution code:
ans = 0
kukan = []
max_l = 0
min_r = 10**9
n = int(input())
for i in range(n):
    l,r = map(int, input().split())
    l,r = l-1,r-1
    ans = max(ans, r-l+1)
    max_l = max(max_l, l)
    min_r = min(min_r, r)
    kukan.append((l,r))
kukan = list(set(kukan))
kukan.sort()

if len(kukan) == 1:
    ans = 2*(min_r-max_l+1)
    print(ans)
    exit()

# maxとminが同じ時は？
# 最大区間を取ってくればいいだけ
min_r_l = None
l,r = kukan.pop()
max_l_r = r
for i in range(len(kukan)):
    if kukan[i][1] == min_r:
        min_r_l = kukan[i][0]
        kukan.pop(i)
        break

if min_r_l is None:
    ans = min_r-max_l+1 + max(r-l+1 for l, r in kukan)
    print(ans)
    exit()

# 累積和
# Lが小さい方からK個取ったときに、残りのRの最小値がほしい
cumsum_r = [float("inf")]
for i in reversed(range(len(kukan))):
    cumsum_r.append(min(cumsum_r[-1], kukan[i][1]))
cumsum_r = cumsum_r[::-1]

# 左 : min_r_l, min_r
# 右 : max_l, max_l_r

for i in range(len(kukan)+1):
    # Lに取らない時
    if i == 0:
        left_l = min_r_l
        right_r = min(max_l_r,cumsum_r[i])
    # 1個以上取る時
    else:
        left_l = max(min_r_l, kukan[i-1][0])
        right_r = min(max_l_r,cumsum_r[i])
    tmp = max(0, min_r-left_l+1) + max(0, right_r-max_l+1)
    ans = max(ans, tmp)

print(ans)

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(sorted(LR,key=lambda x:x[0]),key = lambda x: x[1])

Lmax = Lsorted[0]
Rmin = Rsorted[0]
if Lmax[2]==Rmin[2]:
    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: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)

    if Rsorted[N-1][2]==Lmax[2]:
        print(-1)
    else:
        print(maxscore)

Submission status: Wrong Answer

Solution code:
N, *LR = map(int, open(0).read().split())
LR = sorted((- (r - l + 1), r, l) for l, r in zip(*[iter(LR)] * 2))


_, min_r, max_l = LR[0]
A = []
for _, r, l in LR:
    max_l, min_r = max(max_l, l), min(min_r, r)
    A.append(max(0, min_r - max_l + 1))

_, min_r, max_l = LR[-1]
B = []
for _, r, l in reversed(LR):
    max_l, min_r = max(max_l, l), min(min_r, r)
    B.append(max(0, min_r - max_l + 1))

B.pop()

print(max(a + b for a, b in zip(A, reversed(B))))

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
N = int(input())

L_R = [list(map(int, input().split())) for i in range(N)]
L_R_sort = sorted(L_R, key=lambda k: k[0])
np_L_R_sort = np.array(L_R_sort)
# print(np_L_R_sort[:2])
# print(np_L_R_sort[:2].min(axis=0)[1])
max_point = 0
for i in range(1, N):
    point = 0

    L_max = np_L_R_sort[:i].max(axis=0)[0]
    R_min = np_L_R_sort[:i].min(axis=0)[1]
    point += max(R_min - L_max + 1, 0)
    L_max = np_L_R_sort[i:].max(axis=0)[0]
    R_min = np_L_R_sort[i:].min(axis=0)[1]
    point += max(R_min - L_max + 1, 0)
    if max_point > point:
        print(max_point)
        sys.exit()
    else:
        max_point = point
print(max_point)

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)


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

set3 = [LR[0][0], LR[0][1]]
set4 = [LR[1][0], LR[1][1]]

LR = sorted(LR[2:], key=lambda x: x[1]-x[0])

for i in range(N-2):
    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 = max(set1[1] - set1[0]+1, 0) + max(set2[1]-set2[0]+1, 0)


set1 = [set3[0], set3[1]]
set2 = [set4[0], set4[1]]
for i in range(N-2):
    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])]

ans2 = max(set1[1] - set1[0]+1, 0) + max(set2[1]-set2[0]+1, 0)

print(max(ans1, ans2))

Submission status: Wrong Answer

Solution code:
n=int(input())
lr=[]
for i in range(n):
	lr.append(list(map(int,input().split())))

dp=[[0,0,0,0] for k in range(n)]
dp[0]=[lr[0][0],lr[0][1],lr[1][0],lr[1][1]]
for i in range(n-2):
	a=max(0,-max(dp[i][0],lr[i+2][0])+min(dp[i][1],lr[i+2][1]))+max(0,dp[i][3]-dp[i][2])+2
	b=max(0,-max(dp[i][2],lr[i+2][0])+min(dp[i][3],lr[i+2][1]))+max(0,dp[i][1]-dp[i][0])+2
	if a>b:
		dp[i+1][0]=max(dp[i][0],lr[i+2][0])
		dp[i+1][1]=min(dp[i][1],lr[i+2][1])
		dp[i+1][2]=dp[i][2]
		dp[i+1][3]=dp[i][3]
	else:
		dp[i+1][0]=dp[i][0]
		dp[i+1][1]=dp[i][1]
		dp[i+1][2]=max(dp[i][2],lr[i+2][0])
		dp[i+1][3]=min(dp[i][3],lr[i+2][1])
tanoshisa=max(0,-dp[n-2][0]+dp[n-2][1])+max(0,-dp[n-2][2]+dp[n-2][3])+2

hikidashi=lr[0]
del lr[0]
lr.append(hikidashi)

dp2=[[0,0,0,0] for k in range(n)]
dp2[0]=[lr[0][0],lr[0][1],lr[1][0],lr[1][1]]
for i in range(n-2):
	a=max(0,-max(dp2[i][0],lr[i+2][0])+min(dp2[i][1],lr[i+2][1]))+max(0,dp2[i][3]-dp2[i][2])+2
	b=max(0,-max(dp2[i][2],lr[i+2][0])+min(dp2[i][3],lr[i+2][1]))+max(0,dp2[i][1]-dp2[i][0])+2
	if a>b:
		dp2[i+1][0]=max(dp2[i][0],lr[i+2][0])
		dp2[i+1][1]=min(dp2[i][1],lr[i+2][1])
		dp2[i+1][2]=dp2[i][2]
		dp2[i+1][3]=dp2[i][3]
	else:
		dp2[i+1][0]=dp2[i][0]
		dp2[i+1][1]=dp2[i][1]
		dp2[i+1][2]=max(dp2[i][2],lr[i+2][0])
		dp2[i+1][3]=min(dp2[i][3],lr[i+2][1])
tanoshisa2=max(0,-dp2[n-2][0]+dp2[n-2][1])+max(0,-dp2[n-2][2]+dp2[n-2][3])+2


print(max(tanoshisa,tanoshisa2))

Submission status: Wrong Answer

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

g1, g2, g3 = [], [], []
M = 0

dif = []

for i in range(n):
    l, r = lr[i][0], lr[i][1]
    dif.append([r-l+1, i])
    M = max(M, r-l+1)
    if g1 == []:
        g1.append(l)
        g1.append(r)
    if r <= g1[0] or l >= g1[1]:
        if g2 == []:
            g2.append(l)
            g2.append(r)
        elif r <= g2[0] or l >= g2[1]:
            g3.append([l, r])
        else:
            g2[0] = max(g2[0], l)
            g2[1] = min(g2[1], r)
    else:
        g1[0] = max(g1[0], l)
        g1[1] = min(g1[1], r)

if g2 == []:
    dif = sorted(dif, key=lambda x: x[0], reverse=True)
    if lr[dif[0][1]][0] == g1[0] or lr[dif[0][1]][1] == g1[1]:
        lr.pop(dif[0][1])
        g4 = []
        for i in range(n-1):
            l, r = lr[i][0], lr[i][1]
            if g4 == []:
                g4.append(l)
                g4.append(r)
            g4[0] = max(g4[0], l)
            g4[1] = min(g4[1], r)
        print(max(M + g1[1]-g1[0]+1, M + g4[1]-g4[0]+1))
    else:
        print(M + g1[1]-g1[0]+1)
elif g3 == []:
    print(max(M, g1[1]-g1[0]+1 + g2[1]-g2[0]+1))
else:
    print(M)

Submission status: Wrong Answer

Solution code:
import bisect, collections, heapq, sys
input = sys.stdin.readline

n = int(input())
problem_list = []
r = 10**9+1
p_list = []
for i in range(n):
    a, b = [ int(v) for v in input().split() ]
    p_list.append(a)
    p_list.append(b)
    problem_list.append([b, a])
problem_list.sort()
problem_list = [ [i[1],i[0]] for i in problem_list ]
problem_list.sort()
p_list.sort()
problem_list = [ ( bisect.bisect_left(p_list,i[0]), bisect.bisect_left(p_list,i[1]) )  for i in problem_list ]

left_list = [ 0 for i in range(2*n) ]
right_list = [ 0 for i in range(2*n) ]
for a, b in problem_list:
    left_list[a] += 1
    right_list[b] += 1

ans = 0
la = problem_list[-1][0]
ra = None
lenr = len(right_list) 
for i in range(lenr):
    if right_list[i] > 0:
        ra = i
        break
lb, rb = -1, 10**6+1

for a, b in problem_list[:-1]:
    
    left_list[a] -= 1
    right_list[b] -= 1
    lb = max(lb,a)
    rb = min(rb,b)

    if left_list[la] == 0:
        for i in range(1,2**n):
            if left_list[la+i] != 0:
                la += i
                break
    if right_list[ra] == 0:
        for i in range(1,2**n):
            if right_list[ra+i] != 0:
                ra += i
                break

    ans = max(ans,(max(p_list[rb]-p_list[lb]+1,0)+max(p_list[ra]-p_list[la]+1,0)))

print(ans)

Submission status: Wrong Answer

Solution code:
def f(li, new):
    tmp_li = [li[0], li[1], new]
    #tmp_li.sort(reverse=True, key=lambda x: x[2])
    l1, r1, d1 = tmp_li[0]
    l2, r2, d2 = tmp_li[1]
    l3, r3, d3 = tmp_li[2]
    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]

    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:
def f(li, new):
    tmp_li = [li[0], li[1], new]
    #tmp_li.sort(reverse=True, key=lambda x: x[2])
    l1, r1, d1 = tmp_li[0]
    l2, r2, d2 = tmp_li[1]
    l3, r3, d3 = tmp_li[2]
    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]

    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
import heapq
m=10**9
n = int(input())
bd = [[0,0] for _ in range(n)]
minr = 10**9+1
secminr = 10**9 +1
minrInd = -1
maxl = 0
maxlInd = -1
maxrange = -1
secmax = -1
thmax = -1
maxi = -1
seci = -1
thi = -1
queue = []
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+1) + maxrange + 1 )
    exit()
tmpmax = 0
if maxi != maxlInd:
    if maxi != minrInd:
        tmpmax = max(0, minr - maxl+1) + maxrange + 1
    elif seci != maxlInd and seci != -1:
        tmpmax = max(0, minr - maxl+1) + secmax + 1
    elif thi != -1:
        tmpmax = max(0, minr - maxl+1) + thmax + 1
elif seci != minrInd and seci != -1:
    tmpmax = max(0, minr - maxl+1) + secmax + 1
elif thi != -1:
    tmpmax = max(0, minr - maxl +1) + thmax + 1

lb1 = bd[minrInd][0]
rb1 = bd[minrInd][1]
lb2 = bd[maxlInd][0]
rb2 = bd[maxlInd][1]

for i in range(n):
    heapq.heappush(queue, (rb1 - bd[i][0] + bd[i][1] - lb2, i))


for j in range(n):
    _, i = heapq.heappop(queue)
    if bd[i][0] <= lb1:
        continue
    elif bd[i][1] >= rb2:
        continue
    elif max(0, rb1 - bd[i][0]+1) + max(0, rb2 - lb2+1) > max(0, rb1 - lb1+1) + max(0, bd[i][1] - lb2+1):
        lb1 = bd[i][0]
    else:
        rb2 = bd[i][1]

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

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(sorted(LR,key=lambda x:x[0]),key = lambda x: x[1])

Lmax = Lsorted[0]
Rmin = Rsorted[0]
if Lmax[2]==Rmin[2]:
    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: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
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))

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

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

Solution code:
N=int(input())
x = [0] * (N)
y = [0] * (N)
z = 0
m_index = 0
m_index2 = 0
for i in range(N):
    x[i],y[i] = map(int,input().split())
    if((y[i] - x[i]) > z):
        z = y[i] - x[i]
        m_index = i
m1 = x[m_index]
m2 = y[m_index]
for i in range(N):
    if(x[i] > m1):
        mm1 = x[i]
    else:
        mm1 = m1
    if(y[i] < m2):
        mm2 = y[i]
    else:
        mm2 = m2  
    if(z > mm2 - mm1):
        z = mm2 - mm1
        m_index2 = i
mm1 = x[m_index2]
mm2 = y[m_index2]

for i in range(N):
    p1 = 0
    p2 = 0
    if((i != m_index) &(i != m_index2)):
        if(x[i] > m1):
            t1 = x[i]
            p1 += x[i] - m1
        else:
            t1 = m1
        if(y[i] < m2):
            t2 = y[i]
            p1 += m2 - y[i] 
        else:
            t2 = m2
        if(x[i] > mm1):
            tt1 = x[i]
            p2 += x[i] - mm1
        else:
            tt1 = mm1
        if(y[i] < mm2):
            tt2 = y[i]
            p2 += mm2 - y[i] 
        else:
            tt2 = mm2
        if(p2 > p1):
            #print('a')
            m1 = t1
            m2 = t2
        else:
            #print('b')
            mm1 = tt1
            mm2 = tt2
    
        

print(m2-m1+mm2-mm1+2)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
n = int(input())

c1 = list(map(int, input().split()))
c2 = list(map(int, input().split()))

c1p = c1[1] - c1[0]
c2p = c2[1] - c2[0]
for _ in range(n-2):
    l, r = map(int, input().split())
    # c1
    _c1p = min(r, c1[1]) - max(l, c1[0])
    _c1p = _c1p if _c1p >= 0 else 0
    sc1p = _c1p + c2p

    # c2
    _c2p = min(r, c2[1]) - max(l, c2[0])
    _c2p = _c2p if _c2p >= 0 else 0
    sc2p = c1p + _c2p

    # new
    _cmp = min(c1[1], c2[1]) - max(c1[0], c2[0])
    _cmp = _cmp if _cmp >= 0 else 0
    _cnp = r - l
    scnp = _cmp + _cnp

    if sc1p >= sc2p and sc1p >= scnp:
        c1[0] = max(l, c1[0])
        c1[1] = min(r, c1[1])
        c1p = c1[1] - c1[0]
    elif sc2p >= sc1p and sc2p >= scnp:
        c2[0] = max(l, c2[0])
        c2[1] = min(r, c2[1])
        c2p = c2[1] - c2[0]
    else:
        c1[0] = max(c1[0], c2[0])
        c1[1] = min(c1[1], c2[1])
        c2[0] = l
        c2[1] = r
        c1p = c1[1] - c1[0]
        c2p = c2[1] - c2[0]

print(c1p + c2p + 2)

Submission status: Wrong Answer

Solution code:
import sys

N = int(input())
inp = []
maxi = 0
ind = -1
for k in range(N):
    L, R = map(int, sys.stdin.readline().split())
    inp.append([L, R])
    if maxi < R - L:
        maxi = R - L
        ind = k


A = inp[ind]
B = None
now = float("inf")
now_len = None
for k in range(0, N):
    if k == ind:
        continue
    mx = max(inp[k][0], A[0])
    mn = min(inp[k][1], A[1])
    if mx <= mn:
        leng = mn - mx + 1
    else:
        leng = 0
    if now > leng:
        now = leng
        now_len = k

B = inp[now_len]

for k in range(0, N):
    if k == now_len or k == ind:
        continue
    mxa = max(inp[k][0], A[0])
    mna = min(inp[k][1], A[1])
    mxb = max(inp[k][0], B[0])
    mnb = min(inp[k][1], B[1])

    if (A[1] - A[0] + 1) - (mna - mxa + 1) > (B[1] - B[0] + 1) - (mnb - mxb + 1):
        B = [mxb, mnb]
    else:
        A = [mxa, mna]

result = (A[1] - A[0] + 1) + (B[1] - B[0] + 1)

# for i in inp:
#     if result < i[1] - i[0] + 1:
#         result = i[1] - i[0] + 1

print(result)

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(rm,l[i][1])
ans2+=max(0,rm-lm+1)
ans3=max(0,min(l[0][1],l[1][1])-max(l[0][0],l[1][0])+1)
lm=-1
rm=10**10
for i in range(2,n):
    lm=max(lm,l[i][0])
    rm=min(rm,l[i][1])
ans3+=max(0,rm-lm+1)
ans4=0
l.sort()
lm=-1
rm=10**10
t=10**10
f=0
for i in range(n):
    lm=max(lm,l[i][0])
    rm=min(rm,l[i][1])
    if lm>=rm:
        f+=1
        lm=-1
        rm=10**10
        if f==2:
            break
    else:
        if f==0:
            t=min(rm-lm+1,t)
ans4=0
if f==1:
    ans4=t+rm-lm+1        
print(max(ans1,ans2,ans3,ans4))

Submission status: Wrong Answer

Solution code:
def f(li, new):
    tmp_li = [li[0], li[1], new]
    tmp_li.sort(reverse=True, key=lambda x: x[2])
    l1, r1, d1 = tmp_li[0]
    l2, r2, d2 = tmp_li[1]
    l3, r3, d3 = tmp_li[2]
    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]

    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

N = int(input())
inp = []
maxi = 0
ind = -1
for k in range(N):
    L, R = map(int, sys.stdin.readline().split())
    inp.append([L, R])
    if maxi < R - L:
        maxi = R - L
        ind = k


A = inp[ind]
B = None
now = float("inf")
now_len = None
for k in range(0, N):
    if k == ind:
        continue
    mx = max(inp[k][0], A[0])
    mn = min(inp[k][1], A[1])
    if mx <= mn:
        leng = mn - mx + 1
    else:
        leng = 0
    if now > leng:
        now = leng
        now_len = k

B = inp[now_len]

for k in range(0, N):
    if k == now_len or k == ind:
        continue
    mxa = max(inp[k][0], A[0])
    mna = min(inp[k][1], A[1])
    mxb = max(inp[k][0], B[0])
    mnb = min(inp[k][1], B[1])

    if (A[1] - A[0] + 1) - (mna - mxa + 1) > (B[1] - B[0] + 1) - (mnb - mxb + 1):
        B = [mxb, mnb]
    else:
        A = [mxa, mna]

result = (A[1] - A[0] + 1) + (B[1] - B[0] + 1)

for i in inp:
    if result < i[1] - i[0] + 1:
        result = i[1] - i[0] + 1

print(result)