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 itertools import accumulate

N = int(input())
LR = [tuple(map(int, input().split())) for _ in range(N)]
LR.sort(key=lambda x: x[1], reverse=True)
LR.sort(key=lambda x: x[0])

L = [LR[i][0] for i in range(N)]
R = [LR[i][1] for i in range(N)]

maxL1 = list(accumulate(L, lambda x, y: max(x, y)))
maxL2 = list(accumulate(L[::-1], lambda x, y: max(x, y)))[::-1]
minR1 = list(accumulate(R[::-1], lambda x, y: min(x, y)))[::-1]
minR2 = list(accumulate(R, lambda x, y: min(x, y)))

ans = 0
for i in range(1, N):
    tmp = 0
    if minR2[i-1] - maxL1[i-1] >= 0:
        tmp += minR2[i-1] - maxL1[i-1] + 1
    if minR1[i] - maxL2[i] >= 0:
        tmp += minR1[i] - maxL2[i] + 1
    ans = max(ans, tmp)

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

L = [LR[i][0] for i in range(N)]
R = [LR[i][1] for i in range(N)]

maxL1 = list(accumulate(L, lambda x, y: max(x, y)))
maxL2 = list(accumulate(L[::-1], lambda x, y: max(x, y)))[::-1]
minR1 = list(accumulate(R[::-1], lambda x, y: min(x, y)))[::-1]
minR2 = list(accumulate(R, lambda x, y: min(x, y)))

for i in range(1, N):
    tmp = 0
    if minR2[i-1] - maxL1[i-1] >= 0:
        tmp += minR2[i-1] - maxL1[i-1] + 1
    if minR1[i] - maxL2[i] >= 0:
        tmp += minR1[i] - maxL2[i] + 1
    ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

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

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

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

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

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

    questions.sort(key=lambda x: x[0])
    overlap_for_most_fun = list(map(calc_overlap_for_most_fun, questions))
    index_most_far = overlap_for_most_fun.index(min(overlap_for_most_fun))
    most_far_q = questions.pop(index_most_far)

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

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

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

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

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

    print(score_fun + score_far)


if __name__ == '__main__':
    answer()

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
    max_l = max(max_l, l)
    min_r = min(min_r, r)
    kukan.append((l,r))
kukan = list(set(kukan))
kukan.sort()

# 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:
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():
    N = int(input())
    W = sorted(list(([tuple(map(int, input().split())) for _ in range(N)])))
    sorted(W, key=lambda x: x[1])

    val_left = [0] * N  # W[:k]
    left = 0
    right = 10 ** 9
    for k in range(N - 1):
        left = max(left, W[k][0])
        right = min(right, W[k][1])
        if left > right:
            break
        val_left[k] = right - left + 1

    val_right = [0] * N  # W[k:]
    left = 0
    right = 10 ** 9
    for k in range(N - 1, 0, -1):
        left = max(left, W[k][0])
        right = min(right, W[k][1])
        if left > right:
            break
        val_right[k - 1] = right - left + 1

    res = 0
    for k in range(N):
        res = max(res, val_left[k] + val_right[k])
    print(res)


if __name__ == '__main__':
    f()

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=l[-1][1]-l[-1][0]+l[n-2][1]-l[n-2][0]+2
print(max(ans1,ans2,ans3,ans4))

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
n = int(input())
lm, rm = 0, 10**10
seg = []
for _ in range(n):
	l, r = map(int, input().split())
	seg.append([l, r])
	lm = max(lm, l)
	rm = min(rm, r)

#print(lm, rm)
fm, lt = 1, 10**9
amb = []
for l, r in seg:
	if rm < l and r < lm:
		print(0)
		sys.exit()
	elif lm == l and rm == r:
		print(rm-lm+1 + max([x[1]-x[0]+1 for x in seg]))
		sys.exit()
	elif rm < l:
		lt = min(lt, r)
	elif r < lm:
		fm = max(fm, l)
	else:
		amb.append([l, r])

#print(fm, lt)

if not amb:
	print(rm-fm+1 + lt-lm+1)

else:
	#print(amb)
	#print(rm, lm)
	amb.sort(key=lambda x: (x[0], x[1]))

	lr_max = [10**10 for _ in range(len(amb))] + [amb[-1][1]]
	lr_max[-2] = amb[-1][1]
	for i in range(len(amb)-2, -1, -1):
		lr_max[i] = min(lr_max[i+1], amb[i][1])

	#print(lr_max)

	ans = 0
	for i in range(len(amb)):
		ans = max(ans, rm-amb[i][0]+1 + lr_max[i+1]-lm+1)

	print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
lr=[[0]*2 for _ in range(n)]
for i in range(n):
    lr[i] = list( map(int,input().split()) )
sortedlr = sorted(lr)

C1L=[sortedlr[i-1][0] for i in range(1,n)]
C2L=[sortedlr[-1][0]]*(n-1)

c1right=sortedlr[0][1]
c2right=sortedlr[-1][1]
C1R=[]
C2R=[]
for i in range(1,n):
    c1right=min(c1right,sortedlr[i-1][1])
    C1R.append(c1right)

    c2right=min(c2right,sortedlr[n-i][1])
    C2R.append(c2right)
C2R.reverse()

print( max( max(0,C1R[i]-C1L[i]+1) + max(0,C2R[i]-C2L[i]+1) for i in range(len(C1R))) )

Submission status: Wrong Answer

Solution code:
n = int(input())
lis = [list(map(int,input().split())) for i in range(n)]
lis.sort(key=lambda x:x[1],reverse=True)
lis.sort(key=lambda x:x[0])
left = lis.pop(0)
lis.sort(key=lambda x:x[1],reverse=True)
right = lis.pop(0)
for i in range(n-2):
    now_left = left[1]-left[0]+1
    now_right = right[1]-right[0]+1
    will_left = max(0,min(left[1],lis[i][1])-max(left[0],lis[i][0])+1)
    will_right = max(0,min(right[1],lis[i][1])-max(right[0],lis[i][0])+1)
    lost_left = now_left-will_left
    lost_right = now_right-will_right
    if lost_left >= lost_right:
        right[1] = min(right[1],lis[i][1])
        right[0] = max(right[0],lis[i][0])
    else:
        left[0] = max(left[0],lis[i][0])
        left[1] = min(left[1],lis[i][1])
print(max(0,left[1]-left[0]+1) + max(0,right[1]-right[0]+1))

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] - 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:
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=l[-1][1]-l[-1][0]+l[n-2][1]-l[n-2][0]+1
print(max(ans1,ans2,ans3,ans4))

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
    max_l = max(max_l, l)
    min_r = min(min_r, r)
    kukan.append((l,r))
kukan.sort()

# 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:
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(key=itemgetter(2))

la = L[0][0]
ra = L[0][1]
lb = L[1][0]
rb = L[1][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) == tc:
        la = max(la,lb)
        ra = min(ra, rb)
        lb = L[i][0]
        rb = 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, L[i][0])
        ra = min(ra, L[i][1])
        
ans = max(0, ra-la+1) + max(0, rb-lb+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

set2 = [LR[0][0], LR[0][1]]
set1 = [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])]

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

print(max(ans1, ans2))

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)
L, R = [], []
for l, r in lr:
    L.append(l)
    R.append(r)
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-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:
n = int(input())
lis = [list(map(int,input().split())) for i in range(n)]
lis.sort(key=lambda x:x[1],reverse=True)
lis.sort(key=lambda x:x[0])
left = lis.pop(0)
lis.sort(key=lambda x:x[1],reverse=True)
right = lis.pop(0)
for i in range(n-2):
    now_left = left[1]-left[0]+1
    now_right = right[1]-right[0]+1
    will_left = max(0,min(left[1],lis[i][1])-max(left[0],lis[i][0])+1)
    will_right = max(0,min(right[1],lis[i][1])-max(right[0],lis[i][0])+1)
    lost_left = now_left-will_left
    lost_right = now_right-will_right
    if lost_left > lost_right:
        right[1] = min(right[1],lis[i][1])
        right[0] = max(right[0],lis[i][0])
    else:
        left[0] = max(left[0],lis[i][0])
        left[1] = min(left[1],lis[i][1])
print(max(0,left[1]-left[0]+1) + max(0,right[1]-right[0]+1))

Submission status: Wrong Answer

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):
  tmp = max(EF[0]-SL1[i]+1,0) + max(EF[i+1]-SL2[i+1]+1,0)
  can.append(tmp)
#print(can)
#print(max(can))
xl = []
for i in range(n):
  xl.append(raw[i][1] - raw[i][0] + 1)
#print(max(xl))
print(max(max(can),max(xl)))

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

n = ri()
ls = rils(n)
ls.sort(key=lambda x: x[1])
res = max(r - l + 1 for l, r in ls)
lmax0 = [ls[0][0]]
rmin0 = [ls[0][1]]
for i in range(1, n - 1):
    lmax0.append(max(lmax0[-1], ls[i][0]))
    rmin0.append(min(rmin0[-1], ls[i][1]))

lmax1 = [ls[-1][0]]
rmin1 = [ls[-1][1]]
for i in range(1, n - 1):
    lmax1.append(max(lmax1[-1], ls[n - i - 1][0]))
    rmin1.append(min(rmin1[-1], ls[n - i - 1][1]))

s0 = [max(0, r - l + 1) for l, r in zip(lmax0, rmin0)]
s1 = [max(0, r - l + 1) for l, r in zip(lmax1, rmin1)]
for x, y in zip(s0, reversed(s1)):
    res = max(res, x + y)
print(res)

Submission status: Wrong Answer

Solution code:
N, *LR = map(int, open(0).read().split())
LR = sorted(zip(*[iter(LR)] * 2), key=lambda x: x[1])

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

max_l, min_r = LR[-1]
B = []
for l, r in reversed(LR):
    max_l, min_r = max(max_l, l), min(min_r, r)
    B.append(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:
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 = {i for i in range(min_n, max_n+1)}
# set2 = {i for i in range(min_n, max_n+1)}
# for i in range(N):
#     tmp = {k for k in range(LR[i][0], LR[i][1]+1)}
#     if len(set1 & tmp) >= len(set2 & tmp):
#         set1 &= tmp
#     else:
#         set2 &= tmp

# print(len(set1) + len(set2))


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

set2 = [LR[0][0], LR[0][1]]
set1 = [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])]

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

print(min(ans1, ans2))

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)

com1 = lcnt + rcnt


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

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

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

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

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

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

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

print(max(com1, com2))

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
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)]

sys.setrecursionlimit(1000000)
mod = 1000000007
class SegmentTree:
    def __init__(self, size, default, op = max):
        self.size = 2**size.bit_length()
        self.dat = [default]*(self.size*2)
        self.op = op

    def update(self, i, x):
        i += self.size
        self.dat[i] = x
        while i > 0:
            i >>= 1
            self.dat[i] = self.op(self.dat[i*2], self.dat[i*2+1])

    def add(self, i, x):
        i += self.size
        self.dat[i] = self.op(self.dat[i], x)
        while i > 0:
            i >>= 1
            self.dat[i] = self.op(self.dat[i], x)

    def get(self, a, b = None):
        if b is None:
            b = a + 1
        l, r = a + self.size, b + self.size
        res = None
        while l < r:
            if l & 1:
                if res is None:
                    res = self.dat[l]
                else:
                    res = self.op(res, self.dat[l])
                l += 1

            if r & 1:
                r -= 1
                if res is None:
                    res = self.dat[r]
                else:
                    res = self.op(res, self.dat[r])
            l >>= 1
            r >>= 1
        return res
def solve():
    n = I()
    p = LIR(n)
    f = defaultdict(lambda : 0)
    p.sort(key = lambda x:x[1])
    lm = [p[-1][0]]
    for i,j in p[:-1]:
        lm.append(max(i,lm[-1]))
    lm = lm[::-1]
    lmax = SegmentTree(n,0)
    rmin = SegmentTree(n,float("inf"),min)
    R = []
    for i in range(n):
        lmax.update(i,p[i][0])
        rmin.update(i,p[i][1])
        R.append(p[i][1])
    for i in range(n):
        x,y = p[i]
        f[x] = 1
        f[y] = 1
    L = list(f.keys())
    L.sort()
    ans = 0
    left = [0,0]
    right = [0,0]
    k = 0
    l = 0
    for i in range(len(L)-1):
        x,y = L[i],L[i+1]
        l = bisect.bisect_right(R,x)
        rl = l
        rr = n
        while rr-rl > 1:
            m = (rr+rl) >> 1
            r = lmax.get(l,m+1)
            if r < y:
                rl = m
            else:
                rr = m
        r = rl
        for m in range(k,l):
            nx,ny = p[m]
            if left == [0,0]:
                left = [nx,ny]
            else:
                if left[0] < nx:
                    left[0] = nx
                if left[1] > ny:
                    left[1] = ny
        k = l
        if r+1 < n:
            right = [lm[r+1],p[r+1][1]]
        else:
            right = [0,0]

        if left[0] >= left[1]:
            if right[0] >= right[1]:
                s = 0
            else:
                s = max(0,right[1]-right[0]+1)
        else:
            if right[0] >= right[1]:
                s = max(0,left[1]-left[0]+1)
            else:
                s = 0
        mid = [lmax.get(l,r+1),rmin.get(l,r+1)]
        s += max(0,mid[1]-mid[0]+1)
        if ans < s:
            ans = s
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

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[-1]
    LR.remove(c1)
    c2 = LR[-1]  # c1 と重なっていない部分が最も長いものを探す
    ma = 0
    for x in LR:
        l, r, n = f(c1, x)
        v = x[2] - n
        if v > ma:
            ma = v
            c2 = x
#    print(LR, c1, c2)
    LR.remove(c2)
    for x in LR:
        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:
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
#print(sch)
if sch >= 3:
    print(ans)
elif sch == 2:
    # ここは合ってる
    LR_ = []
    pl = 0
    for l, r in LR:
        if pl >= l:
            pass
        else:
            LR_.append([l, r])
        pl = l
    assert len(LR_) >= 2
    LR = LR_
    Ll, Lr = LR[0]
    Rl, Rr = LR[-1][0], LR[1][1]
    ans = max(ans, max(Rr-Rl, 0) + Lr-Ll)
    for i, (l, r) in enumerate(LR[1:-1], 1):
        Ll = l
        Rr = LR[i+1][1]
        ans = max(ans, max(Rr-Rl, 0) + max(Lr-Ll, 0))
    print(ans)
else:
    Ll, Lr = 0, float("inf")
    Ls = []
    for l, r in LR[:-1]:
        Ll = max(Ll, l)
        Lr = min(Lr, r)
        Ls.append(Lr - Ll)
    Rs = []
    Rl, Rr = 0, float("inf")
    for l, r in LR[:0:-1]:
        Rl = max(Rl, l)
        Rr = min(Rr, r)
        Rs.append(Rr - Rl)
    Rs.reverse()
    for l, r in zip(Ls, Rs):
        ans = max(ans, l + r)

    LR.sort(key=itemgetter(0))
    Lr = float("inf")
    Ls = []
    for l, r in LR[:-1]:
        Ll = l
        Lr = min(Lr, r)
        Ls.append(Lr-Ll)
    Rs = []
    Rl, Rr = 0, float("inf")
    for l, r in LR[:0:-1]:
        Rl = max(Rl, l)
        Rr = min(Rr, r)
        Rs.append(Rr - Rl)
    Rs.reverse()
    for l, r in zip(Ls, Rs):
        ans = max(ans, l+r)

    print(ans)

Submission status: Wrong Answer

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

A = [L[0],R[0]]
B = [L[1],R[1]]
val = [0,0,0]

for i in range(2,N):
    l = L[i]
    r = R[i]
    tmpA = [max(l,A[0]),min(r,A[1])]
    val[0] = tmpA[1]-tmpA[0] + B[1]-B[0]+2
    tmpB = [max(l,B[0]),min(r,B[1])]
    val[1] = tmpB[1]-tmpB[0] + A[1]-A[0]+2
    tmpC = [max(A[0],B[0]),min(A[1],B[1])]
    val[2] = tmpC[1]-tmpC[0] + l-r + 2
    maxval = max(val)
    if maxval == val[0]:
        A = tmpA
    elif maxval == val[1]:
        B = tmpB
    else:
        A = tmpC
        B = [l,r]
        
ans = A[1]-A[0]+B[1]-B[0]+2
print(max(0,ans))

Submission status: Wrong Answer

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(key=itemgetter(2))

la = L[0][0]
ra = L[0][1]
lb = L[1][0]
rb = L[1][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(0, ra-la+1) + max(0, rb-lb+1)

la = L[0][0]
ra = L[0][1]
lb = L[1][0]
rb = L[1][1]

for i in range(2, N, 2):
    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]
        
for i in range(3, N, 2):
    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)