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

seg.sort(key=lambda x: (x[0], x[1]))
mins = [seg[-1][1]]
for i in range(n-2, -1, -1):
	mins.append(min(mins[-1], seg[i][1]))
mins.reverse()

ans = 0
for i in range(n):
	l, r = seg[i]
	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 i < n-1:
		ans = max(ans, max(0, rm-l+1) + max(0, mins[i+1]-lm+1))

print(max(ans, rm-lm+1 + max([x[1]-x[0]+1 for x in seg])))

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
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)
ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

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)

seg.sort(key=lambda x: (x[0], x[1]))
mins = [seg[-1][1]]
for i in range(n-2, -1, -1):
	mins.append(min(mins[-1], seg[i][1]))
mins.reverse()

ans = 0
for i in range(n):
	l, r = seg[i]
	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 i < n-1:
		ans = max(ans, max(0, rm-l+1) + max(0, mins[i+1]-lm+1))

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[1], reverse=True)
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)

ans1 = max(ans_ls)

p1 = ls[-1][0]
p2 = min_ls2[0]
ans2 = max(p2 - p1 + 1, 0)
length = 0
for k in ls:
    length = max(k[1]-k[0], length)

ans2 += length
print(max(ans1, ans2))

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
Lmax = max([l for l, r in LR])
Rmin = min([r for l, r in LR])

sLR = sorted(LR, key=lambda x:(max(x[1] - Lmax, 0), - max(Rmin - x[0], 0)))  
L = [0] * N

l,r = sLR[0][0], sLR[0][1]
L[0] = r - l + 1
for itr, val in enumerate(sLR[1:]):
  l = max(l, val[0])
  r = min(r, val[1])
  if l > r:
    break
  else:
    L[itr + 1] = r - l + 1
  
sLR = sLR[::-1]
R = [0] * N

l,r = sLR[0][0], sLR[0][1]
R[0] = r - l + 1
for itr, val in enumerate(sLR[1:]):
  l = max(l, val[0])
  r = min(r, val[1])
  if l > r:
    break
  else:
    R[itr + 1] = r - l + 1

ans = 0  
for l, r in zip(L[:-1], R[::-1][1:]):
  ans = max(ans, l + r) 

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
Lmax = max([l for l, r in LR])
Rmin = min([r for l, r in LR])

sLR = sorted(LR, key=lambda x:(max(x[1] - Lmax, 0), max(- Rmin + x[0], 0)))  
L = [0] * N

l,r = sLR[0][0], sLR[0][1]
L[0] = r - l + 1
for itr, val in enumerate(sLR[1:]):
  l = max(l, val[0])
  r = min(r, val[1])
  if l > r:
    break
  else:
    L[itr + 1] = r - l + 1
  
sLR = sLR[::-1]
R = [0] * N

l,r = sLR[0][0], sLR[0][1]
R[0] = r - l + 1
for itr, val in enumerate(sLR[1:]):
  l = max(l, val[0])
  r = min(r, val[1])
  if l > r:
    break
  else:
    R[itr + 1] = r - l + 1

ans = 0  
for l, r in zip(L[:-1], R[::-1][1:]):
  ans = max(ans, l + r) 

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)][::-1]
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)

another_length = LR[0][1] - LR[0][0] + 1
left_an = LR[0][0]
right_an = LR[0][1]

point = ma + another_length
LR.pop(0)
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:
# -*- coding: utf-8 -*-

import sys
from operator import itemgetter, add

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

def compress(A):
    """ 座標圧縮 """

    zipped, unzipped = {}, {}
    for i, a in enumerate(sorted(set(A))):
        zipped[a] = i
        unzipped[i] = a
    return zipped, unzipped

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

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

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

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

def bisearch_max(mn, mx, func):
    """ 条件を満たす最大値を見つける二分探索 """

    ok = mn
    ng = mx
    while ok+1 < ng:
        mid = (ok+ng) // 2
        if func(mid):
            # 上を探しに行く
            ok = mid
        else:
            # 下を探しに行く
            ng = mid
    return ok

def bisearch_min(mn, mx, func):
    """ 条件を満たす最小値を見つける二分探索 """

    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            # 下を探しに行く
            ok = mid
        else:
            # 上を探しに行く
            ng = mid
    return ok

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

zipped, unzipped = compress(A)

LR.sort(key=itemgetter(0))
LR.sort(key=itemgetter(1))

l1 = LR[0][0]
r1 = LR[0][1]

l2 = 0
r2 = INF
st1 = SegTree(len(zipped), add, 0)
st2 = SegTree(len(zipped), add, 0)
for i in range(1, N):
    l, r = LR[i]
    l2 = max(l2, l)
    r2 = min(r2, r)
    st1.update(zipped[l], st1.get(zipped[l])+1)
    st2.update(zipped[r], st2.get(zipped[r])+1)

def check1(m):
    return st1.query(m, len(zipped)) == 0

def check2(m):
    return st2.query(0, m+1) == 0

ans = (r1-l1+1) + (r2-l2+1)
for i in range(1, N-1):
    l, r = LR[i]
    l1 = max(l1, l)
    r1 = min(r1, r)
    st1.update(zipped[l], st1.get(zipped[l])-1)
    st2.update(zipped[r], st2.get(zipped[r])-1)
    if st1.get(zipped[l]) == 0:
        idx = bisearch_min(-1, len(zipped), check1) - 1
        l2 = unzipped[idx]
    if st2.get(zipped[r]) == 0:
        idx = bisearch_max(0, len(zipped)+1, check2) + 1
        r2 = unzipped[idx]
    ans = max(ans, (r1-l1+1) + (r2-l2+1))
print(ans)

Submission status: Wrong Answer

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

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

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

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

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

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


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

import sys
from operator import itemgetter, add

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

def compress(A):
    """ 座標圧縮 """

    zipped, unzipped = {}, {}
    for i, a in enumerate(sorted(set(A))):
        zipped[a] = i
        unzipped[i] = a
    return zipped, unzipped

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

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

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

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

def bisearch_max(mn, mx, func):
    """ 条件を満たす最大値を見つける二分探索 """

    ok = mn
    ng = mx
    while ok+1 < ng:
        mid = (ok+ng) // 2
        if func(mid):
            # 上を探しに行く
            ok = mid
        else:
            # 下を探しに行く
            ng = mid
    return ok

def bisearch_min(mn, mx, func):
    """ 条件を満たす最小値を見つける二分探索 """

    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            # 下を探しに行く
            ok = mid
        else:
            # 上を探しに行く
            ng = mid
    return ok

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

zipped, unzipped = compress(A)

LR.sort(key=itemgetter(0))
# LR.sort(key=itemgetter(1))

l1 = LR[0][0]
r1 = LR[0][1]

l2 = 0
r2 = INF
st1 = SegTree(len(zipped), add, 0)
st2 = SegTree(len(zipped), add, 0)
for i in range(1, N):
    l, r = LR[i]
    l2 = max(l2, l)
    r2 = min(r2, r)
    st1.update(zipped[l], st1.get(zipped[l])+1)
    st2.update(zipped[r], st2.get(zipped[r])+1)

def check1(m):
    return st1.query(m, len(zipped)) == 0

def check2(m):
    return st2.query(0, m+1) == 0

ans = (r1-l1+1) + (r2-l2+1)
for i in range(1, N-1):
    l, r = LR[i]
    l1 = max(l1, l)
    r1 = min(r1, r)
    st1.update(zipped[l], st1.get(zipped[l])-1)
    st2.update(zipped[r], st2.get(zipped[r])-1)
    if st1.get(zipped[l]) == 0:
        idx = bisearch_min(-1, len(zipped), check1) - 1
        l2 = unzipped[idx]
    if st2.get(zipped[r]) == 0:
        idx = bisearch_max(0, len(zipped)+1, check2) + 1
        r2 = unzipped[idx]
    ans = max(ans, (r1-l1+1) + (r2-l2+1))
print(ans)

Submission status: Wrong Answer

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

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

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

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

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

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


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
lr = [list(map(int, input().split())) for _ in range(N)]
lr.sort(key = lambda x: (x[0], -x[1]))
#print(lr)
dpx = [0] * N
dpy = [0] * N
dpx[0] = lr[0][1] - lr[0][0] + 1
def check(x, y):
  if x[1] >= y[0]:
    return [max(x[0], y[0]), min(x[1], y[1])]
  else: return [-1, -1]
ran = [0, 10 ** 9]
for i in range(N - 1, -1, -1):
  ran = check(lr[i], ran)
  dpy[i] = ran[1] - ran[0] + 1
  #print(lr[i])
ran = lr[0]
for i in range(N):
  ran = check(lr[i], ran)
  dpx[i] = ran[1] - ran[0] + 1
  #print(lr[i])
#print(dpx, dpy)
res = 0
for i in range(N - 1):
  res = max(dpx[i] + dpy[i + 1], res)
print(res)

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N = I()
    LR=LLIN_(N)
    L_sort = sorted(LR)
    R_sort = sorted(LR,key=lambda x: x[1])
    
    # print(L_sort)
    # print()
    # print(R_sort)
    
    def get_fun(A,i):
        left = -1
        right = 10**9+7
        for l,r in A[:i]:
            left=max(left,l)
            right=min(right, r)
        res = max(0,right-left+1)

        left = -1
        right = 10**9+7
        for l,r in A[i:]:
            left=max(left,l)
            right=min(right, r)
        res += max(0,right-left+1)
        
        return res
    
    ans = 0
    left = 0
    right = N
    while left+2<right:
        ml = (left*2+right)//3
        mr = (left+right*2)//3
        if get_fun(L_sort,ml)<get_fun(L_sort,mr):
            left=ml
        else:
            right=mr
    ans = get_fun(L_sort,(left+right)//2)

    left = 0
    right = N
    while left+2<right:
        ml = (left*2+right)//3
        mr = (left+right*2)//3
        if get_fun(R_sort,ml)<get_fun(R_sort,mr):
            left=ml
        else:
            right=mr
    ans = max(ans,get_fun(R_sort,(left+right)//2))

    m =max(LR,key=lambda x: x[1]-x[0])
    i = LR.index(m)
    left = 0
    right = 10**9+4
    for j,(l,r) in enumerate(LR):
        if i==j:
            continue
        left=max(left,l)
        right=min(right, r)
    ans = max(ans, max(0,(right-left+1))+m[1]-m[0])


    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
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)
tmp = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    else:
        tmp.append(lr[i])
lr = tmp[::-1]
R = lr[0][1]
tmp = [lr[0]]
for l, r in lr[1:]:
    if R<=r:
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]
ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(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())
LR = [tuple(map(int, input().split())) for _ in range(N)]

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

i1, i2, ans1 = 0, 1, LR[0][1] - LR[0][0]
while i2 + 1 < N and LR[i2 + 1][1] - LR[i2 + 1][0] == ans1:
    i2 += 1
ans2 = LR[i2][1] - LR[i2][0]
L1, R1, L2, R2 = LR[i1][0], LR[i1][1], LR[i2][0], LR[i2][1]

for i in range(N - 1, 0, -1):
    if not i == i2:
        diff1 = max(R1 - L1 + 1, 0) - \
            max(min(LR[i][1], R1) - max(LR[i][0], L1) + 1, 0)
        diff2 = max(R2 - L2 + 1, 0) - \
            max(min(LR[i][1], R2) - max(LR[i][0], L2) + 1, 0)
        if diff1 < diff2:
            L1, R1 = max(LR[i][0], L1), min(LR[i][1], R1)
        elif diff1 == diff2:
            if max(R1 - L1 + 1, 0) > max(R2 - L2 + 1, 0):
                L2, R2 = max(LR[i][0], L2), min(LR[i][1], R2)
            else:
                L1, R1 = max(LR[i][0], L1), min(LR[i][1], R1)
        else:
            L2, R2 = max(LR[i][0], L2), min(LR[i][1], R2)

print(max(R1 - L1 + 1, 0) + max(R2 - L2 + 1, 0))

Submission status: Wrong Answer

Solution code:
N = int(input())
questions = [list(map(int,input().split())) for _ in range(N)]
questions.sort()
#print(questions)
ans = 0
for i in range(N - 1):
    if i == 0:
        left, right = questions[0][0] , questions[0][1]
        s1 = right - left + 1
        left, right = max(questions[i + 1][0], questions[N - 1][0]), min(questions[i + 1][1], questions[N - 1][1])
        s2 = right - left + 1
    elif i == N - 2:
        left, right = max(questions[0][0], questions[i][0]), min(questions[0][1], questions[i][1])
        s1 = right - left + 1
        left, right = questions[N - 1][0], questions[N - 1][1]
        s2 = right - left + 1
    else:
        left , right = max(questions[0][0] , questions[i][0]) , min(questions[0][1] , questions[i][1])
        s1 = right - left + 1
        left , right = max(questions[i + 1][0] , questions[N - 1][0]) , min(questions[i + 1][1] , questions[N - 1][1])
        s2 = right - left + 1

    tmp_ans = s1 + s2
    if tmp_ans > ans:
        ans = tmp_ans
print(ans)

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:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    for i in range(N):
        LR[i][1] -= mid_r-mid_l
    LR_ = []
    pl = 0
    for l, r in LR:
        if pl >= l:
            pass
        else:
            LR_.append([l, r])
        pl = l
    if not len(LR_) >= 2:
        print(ans + mid_r - mid_l)
        exit()
    an = 0
    LR, LR_ = LR_, LR
    Ll, Lr = LR[0]
    Rl, Rr = LR[-1][0], LR[1][1]
    an = max(an, max(Rr-Rl, 0) + Lr-Ll)
    for i, (l, r) in enumerate(LR[1:-1], 1):
        Ll = l
        Rr = LR[i+1][1]
        an = max(an, max(Rr-Rl, 0) + max(Lr-Ll, 0))
    an += (mid_r - mid_l) * 2
    print(an)

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,1-max(dp[i][0],lr[i+2][0])+min(dp[i][1],lr[i+2][1]))+max(0,1+dp[i][3]-dp[i][2])
	b=max(0,1-max(dp[i][2],lr[i+2][0])+min(dp[i][3],lr[i+2][1]))+max(0,1+dp[i][1]-dp[i][0])
	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,1-dp[n-2][0]+dp[n-2][1])+max(0,1-dp[n-2][2]+dp[n-2][3])

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,1-max(dp2[i][0],lr[i+2][0])+min(dp2[i][1],lr[i+2][1]))+max(0,1+dp2[i][3]-dp2[i][2])
	b=max(0,1-max(dp2[i][2],lr[i+2][0])+min(dp2[i][3],lr[i+2][1]))+max(0,1+dp2[i][1]-dp2[i][0])
	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,1-dp2[n-2][0]+dp2[n-2][1])+max(0,1-dp2[n-2][2]+dp2[n-2][3])


print(max(tanoshisa,tanoshisa2))

Submission status: Wrong Answer

Solution code:
import sys
import collections
from builtins import min


def solve():
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    n = int(input().rstrip('\n'))
    lr = []
    for i in range(n):
        l, r = list(map(int, input().rstrip('\n').split()))
        lr.append([l, r, abs(l - r) + 1])
    lr.sort(key=lambda x: x[2])
    lr = collections.deque(lr)
    mlr = [[0] * 3 for _ in range(2)]

    l_r = lr.pop()
    mlr[0][0] = l_r[0]
    mlr[0][1] = l_r[1]
    mlr[0][2] = l_r[2]

    l_r = lr.popleft()
    mlr[1][0] = l_r[0]
    mlr[1][1] = l_r[1]
    mlr[1][2] = l_r[2]

    while lr:

        l_r = lr.popleft()
        ab1 = -(10 ** 15)
        ab2 = -(10 ** 15)
        if mlr[0][1] >= l_r[0]:
            ab1 = abs(max(l_r[0], mlr[0][0]) - min(l_r[1], mlr[0][1])) + 1
        if mlr[1][1] >= l_r[0]:
            ab2 = abs(max(l_r[0], mlr[1][0]) - min(l_r[1], mlr[1][1])) + 1

        if mlr[0][2] - ab1 > mlr[1][2] - ab2:
            mlr[1][0] = max(mlr[1][0], l_r[0])
            mlr[1][1] = min(mlr[1][1], l_r[1])
            mlr[1][2] = ab2
        elif mlr[0][2] - ab1 <= mlr[1][2] - ab2:
            mlr[0][0] = max(mlr[0][0], l_r[0])
            mlr[0][1] = min(mlr[0][1], l_r[1])
            mlr[0][2] = ab1
    print(mlr[0][2] + mlr[1][2])


if __name__ == '__main__':
    solve()

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[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)
    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
    minR = Lmax[1]
    for i in range(N):
        if Lsorted[i][2]!=Rmin[2]:
            minR = min(Lsorted[i][0],minR)
            nowmaxL = Lsorted[i+1][1]
            maxscore =max(maxscore, max(minR-Lmax[0]+1,0) + max(Rmin[1]-nowmaxL+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)