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())
LR = [list(map(int,input().split())) for _ in range(N)]

ML = max(LR)[0]
mR = min(LR,key=lambda x:x[1])[1]

if max(LR) != [ML,mR]:
    LR.sort(key=lambda x:x[1])
    L = [LR[i][0] for i in range(N)]
    for i in range(N):
        r = LR[i][1]
        if ML <= r:
            break

    L_ = [0]*N
    for j in range(N):
        L_[j] = max(L[j],L_[j-1])

    ans = 0
    for j in range(i,N):
        ans = max(ans,LR[j][1]-ML+1+mR-L_[j-1]+1)

else:
    ans = mR-ML+1
    for i in range(N):
        ans = max(ans,mR-ML+1+LR[i][1]-LR[i][0]+1)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
p = [ list(map(int, input().split())) for _ in range(n) ]
dp = [0] * n
aL, aR, bL, bR = p[0][0], p[0][1], p[1][0], p[1][1]
dp[1] = (aR - aL) + (bR - bL)
for i in range(2, n):
  caseA = (min(aR, p[i][1]) - max(aL, p[i][0])) + (bR - bL)
  caseB = (min(bR, p[i][1]) - max(bL, p[i][0])) + (aR - aL)
  if caseA >= caseB:
    dp[i] = caseA
    aL, aR = max(aL, p[i][0]), min(aR, p[i][1])
  else:
    dp[i] = caseB
    bL, bR = max(bL, p[i][0]), min(bR, p[i][1])
    
print(dp[n-1]+2)

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(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
it=[]
for _ in range(n):
    it.append(list(map(int,input().split())))
it.sort()
ac=[i+[j] for j,i in enumerate(it[:])]
ac.sort(key=lambda x:x[1])
bc=[i+[j] for j,i in enumerate(it[:])]
bc.sort(key=lambda x:x[0],reverse=True)

maa=0
mi=bc[0][0]
ma=ac[0][1]
a=0
b=0
for i in range(n):
    if i==ac[0][2]:
        ma=ac[1][1]
        a=1
    if i==bc[0][2]:
        mi=bc[1][0]
        b=1
   # print(ma-mi+1)
    maa=max(ma-mi+1,maa)
    if a:
        ma=ac[0][1]
    if b:
        mi=bc[0][0]

aa=[0]*n
bb=[0]*n
aa[0]=it[0][1]-it[0][0]+1
mi=it[0][0]
ma=it[0][1]
for i in range(1,n-1):
    mi=max(mi,it[i][0])
    ma=min(ma,it[i][1])
    so=ma-mi+1
    if so<0:
        so=0
    aa[i]=so

bb[-1]=it[-1][1]-it[-1][0]+1
mi=it[-1][0]
ma=it[-1][1]

for i in range(n-2,0,-1):
    mi=max(mi,it[i][0])
    ma=min(ma,it[i][1])
    so=ma-mi+1
    if so<0:
        so=0
    bb[i]=so
ma=aa[0]+bb[1]
for i in range(1,n-1):
    ma=max(ma,aa[i]+bb[i+1])
print(max(ma,maa))

Submission status: Wrong Answer

Solution code:
n=int(input())
l=[]
for i in range(n):
    l.append(list(map(int,input().split())))
m=0
for i in l:
    m=max(m,i[1]-i[0]+1)
print(m)

Submission status: Wrong Answer

Solution code:
import heapq
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))

def main():
    n = getN()
    quiz = []
    for i in range(n):
        quiz.append(getList())
    quiz.sort(key=lambda x:x[0])
    hel, her = [], []
    for qu in quiz:
        heapq.heappush(hel, -qu[0])
        heapq.heappush(her, qu[1])

    ans = 0

    # print(hel, her)
    # l切り取り、r固定
    old_rend = heapq.heappop(her)
    old_lend = quiz[-1][0]
    new_lend = quiz[0][0]
    new_rend = quiz[0][1]
    if new_rend == old_rend:
        old_rend = heapq.heappop(her)

    tmp_d = old_rend - old_lend + new_rend - new_lend
    if ans < tmp_d:
        ans = tmp_d
    # =============初期化及び初期計算========================
    for qu in quiz[1:-1]:
        # print(qu, ans)
        new_lend = qu[0]
        if qu[1] == old_rend:
          old_rend = heapq.heappop(her)
        if new_rend > qu[1]:
            new_rend = qu[1]
        tmp_d = old_rend - old_lend + new_rend - new_lend
        if ans < tmp_d:
            ans = tmp_d
            # print("b")

    # print("=========================================================")
    # print(ans)
    quiz.sort(key=lambda x: x[1], reverse=True)

    # r切り取り、l固定
    old_lend = -heapq.heappop(hel)
    old_rend = quiz[-1][1]
    new_lend = quiz[0][0]
    new_rend = quiz[0][1]
    if new_lend == old_lend:
        old_lend = -heapq.heappop(hel)
    tmp_d = old_rend - old_lend + new_rend - new_lend
    if ans < tmp_d:
        ans = tmp_d
    # print(quiz, old_rend, old_lend, new_rend, new_lend)
    # =============初期化及び初期計算========================
    for qu in quiz[1:-1]:
        new_rend = qu[1]
        # print(qu, ans)
        if qu[0] == old_lend:
            old_lend = -heapq.heappop(hel)
        if new_lend < qu[0]:
            new_lend = qu[0]
        tmp_d = old_rend - old_lend + new_rend - new_lend
        # print(quiz, old_rend, old_lend, new_rend, new_lend)
        if ans < tmp_d:
            ans = tmp_d
            # print("a")

    print(ans + 2)
    return

if __name__ == "__main__":
    main()

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

ans = 0
for j in range(4):
    
    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])) + rb-lb
        tb = max(0, min(rb, L[i][1])-max(lb, L[i][0])) + ra-la
        tc = max(0, min(ra, rb)-max(la,lb)) + L[i][1]-L[i][0]
        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))
    if j == 0:
        L.reverse()
    elif j == 1:
        L.sort(key=itemgetter(2))
    else:
        L.reverse()


print(ans)

Submission status: Wrong Answer

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

N = int(input())
L = [list(map(int, input().split())) for _ in range(N)]


cand = []
L = sorted(L, key=lambda x: x[0])
for pivot in range(1, N):
    low_1, high_1 = L[0]
    for i in range(pivot):
        low_1 = max(low_1, L[i][0])
        high_1 = min(high_1, L[i][1])
    low_2, high_2 = L[-1]
    for i in range(pivot, N):
        low_2 = max(low_2, L[i][0])
        high_2 = min(high_2, L[i][1])
    p_1=max(high_1-low_1,0)
    p_2 = max(high_2-low_2,0)
    ans = p_1+p_2
    cand.append(ans)
print(max(cand))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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])
lr.sort(key=lambda x:x[1])
mae=[]
l=0
r=10**9
for i in range(n):
    ll,rr=lr[i]
    l=max(ll,l)
    r=min(rr,r)
    mae.append(r-l+1)

usi=[]
l=0
r=10**9+1
for i in range(n-1,-1,-1):
    ll,rr=lr[i]
    l=max(ll,l)
    r=min(rr,r)
    usi.append(r-l+1)
usi.reverse()

ans=0
mae.insert(0,0)
mae.append(0)
usi.append(0)
usi.insert(0,0)
for i in range(n-1):
    ans=max(mae[i]+usi[i+1],ans)

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, LR):
    LR.sort(key=lambda x: x[1])
    LR.sort(key=lambda x: x[0])


    lc = []
    l = 0
    r = INF
    for i in range(N):
        l_, r_ = LR[i]
        l = max(l, l_)
        r = min(r, r_)
        lc.append((l, r))
    
    rc = []
    l = 0
    r = INF
    for i in range(N-1, -1, -1):
        l_, r_ = LR[i]
        l = max(l, l_)
        r = min(r, r_)
        rc.append((l, r))
    
    def c(l, r):
        return max(0, r-l+1)

    ans = 0
    for i in range(N-1):
        ans = max(ans, c(*lc[i]) + c(*rc[N-1-1-i]))
    for i in range(N):
        tmp = c(*LR[i])
        l, r = (0, INF)
        if i != 0:
            l = max(l, lc[i-1][0])
            r = min(r, lc[i-1][1])
        if i != N-1:
            l = max(l, lc[N-1-i][0])
            r = min(r, lc[N-1-i][1])
        tmp += c(l, r)
        ans = max(ans, tmp)

    return ans


def main():
    N = read_int()
    LR = [read_int_n() for _ in range(N)]
    print(slv(N, LR))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ls = []
rs = []
ans = 0
for i,(l,r) in enumerate(LR):
    ls.append((l,i))
    rs.append((r,i))
    ans = max(ans, r-l+1)
ls.sort()
rs.sort(reverse=True)

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

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

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

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
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
    return (l, r, r-l+1)


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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from itertools import accumulate


def calc(tasks):
    tasks_l, tasks_r = zip(*tasks)
    tasks_r_acc_fwd = list(accumulate(tasks_r, func=min))
    tasks_r_acc_bwd = list(reversed(list(accumulate(reversed(tasks_r), func=min))))
    # print(tasks)
    # print(tasks_r_acc_fwd)
    # print(tasks_r_acc_bwd)

    right_max_l = tasks_l[-1]
    score = 0
    for i in range(1, n):
        left_max_l = tasks_l[i - 1]
        left_min_r = tasks_r_acc_fwd[i - 1]
        right_min_r = tasks_r_acc_bwd[i]
        tmp_score = max(0, left_min_r - left_max_l + 1) + max(0, right_min_r - right_max_l + 1)
        score = max(score, tmp_score)
    return score


n = int(input())
appeared_lr = set()
tasks = []
for line in sys.stdin:
    l, r = list(map(int, line.split()))
    appeared_lr.add(l)
    appeared_lr.add(r)
    tasks.append((l, r))

tasks.sort()
ans1 = calc(tasks)

tasks.sort(key=lambda lr: (lr[0], -lr[1]))
ans2 = calc(tasks)

tasks.sort(key=lambda lr: (lr[1] - lr[0], lr[0], lr[1]))
ans3 = calc(tasks)

print(max(ans1, ans2, ans3))

Submission status: Wrong Answer

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

import sys
import copy


input = sys.stdin.readline


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

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

    q.sort()
    f = q.pop()
    s = q.pop(0)

    for a in q:
        ln = cal(f, [0, 10**9])
        lm = cal(s, [0, 10**9])
        n = cal(f, a)
        m = cal(s, a)
        if n+lm > ln+m:
            f[0] = max(f[0], a[0])
            f[1] = min(f[1], a[1])
        elif n == m:
            if ln > lm:
                f[0] = max(f[0], a[0])
                f[1] = min(f[1], a[1])
            else:
                s[0] = max(s[0], a[0])
                s[1] = min(s[1], a[1])

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


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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ls = []
rs = []
for i,(l,r) in enumerate(LR):
    ls.append((l,i))
    rs.append((r,i))
ls.sort()
rs.sort(reverse=True)

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

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

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

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
secondlist=[0 for i in range(n)]
for i in range(n):
    a,b=map(int,input().split())
    secondlist[i]=(a,b)
secondlist=sorted(secondlist,key=lambda x:x[1],reverse=True)
secondlist2=sorted(secondlist,key=lambda x:x[1])

mini1=secondlist[0][0]
mini2=secondlist2[0][0]
max1=secondlist[0][1]
max2=secondlist2[0][1]
#min1,max1,で最初の試合の時の人数を抑える
#min2,max2,で次の試合の時の人数を抑える
anslist1=[0 for i in range(n)]
for i in range(n-1):
    mini1=max(mini1,secondlist[i][0])
    max1=min(max1,secondlist[i][1])
    anslist1[i]=max(max1-mini1+1,0)
anslist2=[0 for i in range(n)]
for i in range(n-1):
    mini2=max(mini2,secondlist2[i][0])
    max2=min(max2,secondlist2[i][1])
    anslist2[i]=max(max2-mini2+1,0)
Anslist=[0 for i in range(n-1)]
for i in range(n-1):
    Anslist[i]=max(anslist1[i]+anslist2[n-2-i],0)
MAX1=max(Anslist)
    
    
secondlist=sorted(secondlist,key=lambda x:x[0],reverse=True)
secondlist2=sorted(secondlist,key=lambda x:x[0])

mini1=secondlist[0][0]
mini2=secondlist2[0][0]
max1=secondlist[0][1]
max2=secondlist2[0][1]
#min1,max1,で最初の試合の時の人数を抑える
#min2,max2,で次の試合の時の人数を抑える
anslist1=[0 for i in range(n)]
for i in range(n-1):
    mini1=max(mini1,secondlist[i][0])
    max1=min(max1,secondlist[i][1])
    anslist1[i]=max(max1-mini1+1,0)
anslist2=[0 for i in range(n)]
for i in range(n-1):
    mini2=max(mini2,secondlist2[i][0])
    max2=min(max2,secondlist2[i][1])
    anslist2[i]=max(max2-mini2+1,0)
Anslist2=[0 for i in range(n-1)]
for i in range(n-1):
    Anslist2[i]=max(anslist1[i]+anslist2[n-2-i],0)
MAX2=max(Anslist)
print(max(MAX1,MAX2))

Submission status: Wrong Answer

Solution code:
import os
import sys
from collections import defaultdict as ddic, Counter, deque
from itertools import combinations, permutations, product
import bisect, heapq

FAST_INPUT = 0
if FAST_INPUT:
    from atexit import register
    from io import BytesIO
 
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
    sys.stdout = BytesIO()
    register(lambda: os.write(1, sys.stdout.getvalue()))
 
rr = lambda: sys.stdin.readline().rstrip('\r\n')
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
MOD = 10**9 + 7

DEBUG = 0
if DEBUG:
    import random
    random.seed(0)
    ri = random.randint

#####

def solve(N, A):
    A.sort()
    B = [None] * N
    my = A[-1][1]
    for i in xrange(N-1, -1, -1):
        x, y = A[i]
        if y < my: my = y
        B[i] = my
    topx = A[-1][0]

    ans = max(y-x for x,y in A)
    botx, boty = A[0]
    for i in xrange(N-1):
        x, y = A[i]
        if x > botx: botx = x
        if y < boty: boty = y
        cand = max(0, boty-botx+1) + max(0, B[i+1]-topx+1)
        if cand > ans: ans = cand
    return ans

#####

N = rri()
A = [rrm() for _ in xrange(N)]
print solve(N, A)

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])
lr.sort(key=lambda x:x[1])
mae=[]
l=0
r=10**9
for i in range(n):
    ll,rr=lr[i]
    l=max(ll,l)
    r=min(rr,r)
    mae.append(r-l+1)

usi=[]
l=0
r=10**9+1
for i in range(n-1,-1,-1):
    ll,rr=lr[i]
    l=max(ll,l)
    r=min(rr,r)
    usi.append(r-l+1)
usi.reverse()

ans=0
for i in range(n-1):
    ans=max(mae[i]+usi[i+1],ans)
ans=max([ans,max(mae),max(usi)])
print(ans)

Submission status: Wrong Answer

Solution code:
import random
n = int(input())

l=[-1]*n
r=[-1]*n

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


join_nums = []
for i in range(n-1):
  for j in range(i+1,n):    
    join_l = max(l[i], l[j])
    join_r = min(r[i], r[j])
    
    tmp = max(0, join_r-join_l+1)
    join_nums.append([[i,j], tmp])
    #print(i,j, tmp)

cur_max = 0
for i in range(50000):
  group01 = random.sample(range(n), random.randrange(n-1))
  if len(group01)==0 or len(group01)==n:
    continue
  #print(group01)
  
  if len(group01)==n-1:
    group01 = list(set(list(range(n))) - set(group01))
  
  if len(group01)==1:
    idx=group01[0]
    group01_num = [r[idx]-l[idx]+1]
    
    group02_num=[]
    for jn in join_nums:
      ti,tj = jn[0][0], jn[0][1]
      if ti not in group01 and tj not in group01:
        group02_num.append(jn[1])
  else:
    group01_num=[]
    group02_num=[]
    for jn in join_nums:
      ti,tj = jn[0][0], jn[0][1]
      if ti in group01 and tj in group01:
        group01_num.append(jn[1])
      elif ti not in group01 and tj not in group01:
        group02_num.append(jn[1])
        
  #print("g1_min", )
  #print("g2_min", )
  sum_min = min(group01_num)+min(group02_num)
  if cur_max<sum_min:
    cur_max=sum_min
  
print(cur_max)
"""
join_nums = sorted(join_nums)
print(join_nums[-5:])
print(join_nums[-1]+join_nums[-2])
"""

Submission status: Wrong Answer

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

N = int(input())
L = [list(map(int, input().split())) for _ in range(N)]


cand = []
L = sorted(L, key=lambda x: x[0])
for pivot in range(1, N):
    low_1, high_1 = L[0]
    for i in range(pivot):
        low_1 = max(low_1, L[i][0])
        high_1 = min(high_1, L[i][1])
    low_2, high_2 = L[-1]
    for i in range(pivot, N):
        low_2 = max(low_2, L[i][0])
        high_2 = min(high_2, L[i][1])
    ans = high_1+high_2-low_1-low_2+2
    cand.append(ans)
print(max(cand))

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
sys.setrecursionlimit(10**9)
def input():
    return sys.stdin.readline().rstrip()

def main():
    N=int(input())
    L=[0]*N
    R=[0]*N
    for i in range(N):
        L[i],R[i]=map(int,input().split())
    si=np.argsort(L)
    A=[L[si[0]],R[si[0]]]
    B=[L[si[N-1]],R[si[N-1]]]
    for i in si:
        a=[max(A[0],L[i]),min(A[1],R[i])]
        b=[max(B[0],L[i]),min(B[1],R[i])]
        if a[1]-a[0]+B[1]-B[0] > b[1]-b[0]+A[1]-A[0]:
            A=a
        else:
            B=b
    print(A[1]-A[0]+B[1]-B[0]+2)


if __name__ == '__main__':
    main()

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):
        # print(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
        # print((left,right))
        for l,r in A[i:]:
            left=max(left,l)
            right=min(right, r)
        res += max(0,right-left+1)
        # print((left,right))
        # print(res)
        
        return res
    
    ans = 0
    left = 0
    right = N
    while left+2<right:
        ml = (left*2+right)//3
        mr = (left+right*2)//3
        # print(left,right,ml,mr)    
        # print(get_fun(L_sort,ml), get_fun(L_sort,mr))
        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))
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
it=[]
for _ in range(n):
    it.append(list(map(int,input().split())))
it.sort()
maa=max([i[1]-i[0]+1 for i in it])
aa=[0]*n
bb=[0]*n
aa[0]=it[0][1]-it[0][0]+1
mi=it[0][0]
ma=it[0][1]
for i in range(1,n-1):
    mi=max(mi,it[i][0])
    ma=min(ma,it[i][1])
    so=ma-mi+1
    if so<0:
        so=0
    aa[i]=so

bb[-1]=it[-1][1]-it[-1][0]+1
mi=it[-1][0]
ma=it[-1][1]

for i in range(n-2,0,-1):
    mi=max(mi,it[i][0])
    ma=min(ma,it[i][1])
    so=ma-mi+1
    if so<0:
        so=0
    bb[i]=so
ma=aa[0]+bb[1]
for i in range(1,n-1):
    ma=max(ma,aa[i]+bb[i+1])
print(max(ma,maa))

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

    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))
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

M.sort()
minR1 = [0]*N
minR2 = [0]*N

tmp = M[0][1]
minR1[0] = tmp
for i in range(1, N):
    tmp = min(M[i][1], tmp)
    minR1[i] = tmp

tmp = M[-1][1]
minR2[-1] = tmp
for i in range(N-2, -1, -1):
    tmp = min(M[i][1], tmp)
    minR2[i] = tmp


ans = 0
for i in range(0, N-1):
    L1 = M[i][0]
    L2 = M[-1][0]
    R1 = minR1[i]
    R2 = minR2[i+1]
    ans = max(ans, R1-L1+1 + R2-L2+1)
    
print(ans)

Submission status: Wrong Answer

Solution code:
import os
import sys
from collections import defaultdict as ddic, Counter, deque
from itertools import combinations, permutations, product
import bisect, heapq

FAST_INPUT = 0
if FAST_INPUT:
    from atexit import register
    from io import BytesIO
 
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
    sys.stdout = BytesIO()
    register(lambda: os.write(1, sys.stdout.getvalue()))
 
rr = lambda: sys.stdin.readline().rstrip('\r\n')
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
MOD = 10**9 + 7

DEBUG = 0
if DEBUG:
    import random
    random.seed(0)
    ri = random.randint

#####

def solve(N, A):
    A.sort()
    B = [None] * N
    my = A[-1][1]
    for i in xrange(N-1, -1, -1):
        x, y = A[i]
        if y < my: my = y
        B[i] = my
    topx = A[-1][0]

    ans = max(y-x for x,y in A)
    botx, boty = A[0]
    for i in xrange(N-1):
        x, y = A[i]
        if x > botx: botx = x
        cand = max(0, boty-botx+1) + max(0, B[i+1]-topx+1)
        if cand > ans: ans = cand
    return ans

#####

N = rri()
A = [rrm() for _ in xrange(N)]
print solve(N, A)