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

L.sort(reverse=True, 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])) + 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))
print(ans)

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)

    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
left = [list(map(int,input().split())) for i in range(n)]
right = []
left.sort(key=lambda x:x[1],reverse=True)
left.sort(key=lambda x:x[0])
  #print(left)

min_right = [0 for i in range(n)]
now = 10 ** 9
for i in range(n):
    now = min(now,left[i][1])
    min_right[i] = now


right_max_left = left[-1][0]
right_min_right = left[-1][1]
left_max_left = 0
left_min_right = 0

ans = 0

for i in range(1,n):
    left_max_left = left[-(i+1)][0]
    left_min_right = min_right[-(i+1)]

    ans = max(ans,max(0,left_min_right-left_max_left+1)+max(0,right_min_right-right_max_left+1))
  #    print(left_max_left,left_min_right,right_max_left,right_min_right)

    right_min_right = min(right_min_right,left[-(i+1)][1])
    right_max_left = max(right_max_left,left[-(i+1)][0])


print(ans)

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)

print(max(ans1, ans2))

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


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

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

    
   


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

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

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

c2right=sortedlr[-1][1]
C2L=[]
C2R=[]
for i in range(n-1,0,-1):
    contest2 = sortedlr[i:]
    c2left =contest2[-1][0]
    c2right=min(c2right,contest2[0][1])
    C2L.append(c2left)
    C2R.append(c2right) 
C2L.reverse()
C2R.reverse()

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

Submission status: Wrong Answer

Solution code:
n = int(input())
left = [list(map(int,input().split())) for i in range(n)]
right = []
left.sort(key=lambda x:x[1])
left.sort(key=lambda x:x[0])
  #print(left)

min_right = [0 for i in range(n)]
now = 10 ** 9
for i in range(n):
    now = min(now,left[i][1])
    min_right[i] = now


right_max_left = left[-1][0]
right_min_right = left[-1][1]
left_max_left = 0
left_min_right = 0

ans = 0

for i in range(1,n):
    left_max_left = left[-(i+1)][0]
    left_min_right = min_right[-(i+1)]

    ans = max(ans,max(0,left_min_right-left_max_left+1)+max(0,right_min_right-right_max_left+1))
  #    print(left_max_left,left_min_right,right_max_left,right_min_right)

    right_min_right = min(right_min_right,left[-(i+1)][1])
    right_max_left = max(right_max_left,left[-(i+1)][0])


print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = [list(map(int, input().split())) for _ in range(N)]
lr.sort()
lr1 = []
amari = []
m = lr[-1][1]-lr[-1][0]+1
for i in range(N-1):
    m = max(m, lr[i][1]-lr[i][0]+1)
    if lr[i][1]>=lr[i+1][1]:
        amari.append(lr[i])
        continue
    lr1.append(lr[i])
lr1.append(lr[-1])
ans1 = [m]
ans2 = [0]
R = lr1[0][1]
for l, r in lr1:
    if l>R:
        ans1.append(m)
    else:
        ans1.append(R-l+1)
L = lr1[-1][0]
for l, r in lr1[::-1]:
    if L>r:
        ans2.append(m)
    else:
        ans2.append(r-L+1)
ans = m
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
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()
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=-float("inf")
    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=-float("inf")
    bb[i]=so
ma=aa[0]+bb[1]
for i in range(1,n-1):
    ma=max(ma,aa[i]+bb[i+1])
print(ma)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()

def resolve():
    n=int(input())
    I=[tuple(map(int,input().split())) for _ in range(n)]
    I.sort(lambda x:x[1])
    forL=[0]*n
    forL[0]=I[0][0]
    backL=[0]*n
    backL[-1]=I[-1][0]
    for i in range(n-1):
        forL[i+1]=max(forL[i],I[i+1][0])
        backL[-i-2]=max(backL[-i-1],I[-i-2][0])

    def calc(i): # iは1からn-1まで
        score=0
        score+=max(I[0][1]-forL[i-1]+1,0)
        score+=max(I[i][1]-backL[i]+1,0)
        return score
    print(max(calc(i) for i in range(1,n)))
resolve()

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(1, N):
    if not i == i2:
        diff1 = R1 - L1 - max(min(LR[i][1], R1) - max(LR[i][0], L1), 0)
        diff2 = R2 - L2 - max(min(LR[i][1], R2) - max(LR[i][0], L2), 0)
        if diff1 < diff2:
            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(R1 - L1 + R2 - L2 + 2)

Submission status: Wrong Answer

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

L, R = LR[0]
temp = R - L + 1
ans1 = [temp]
for i in range(1, N-1):
    if L < LR[i][0]:
        temp -= LR[i][0] - L
        L = LR[i][0]
    if R > LR[i][1]:
        temp -= R - LR[i][1]
        R = LR[i][1]
    if temp > 0:
        ans1.append(temp)
    else:
        ans1 += [0] * (N-i-1)

L, R = LR[-1]
temp = R - L + 1
ans2 = [temp]
for i in range(1, N-1):
    if L < LR[-i-1][0]:
        temp -= LR[-i-1][0] - L
        L = LR[-i-1][0]
    if R > LR[-i-1][1]:
        temp -= R - LR[-i-1][1]
        R = LR[-i-1][1]
    if temp > 0:
        ans2.append(temp)
    else:
        ans2 += [0] * (N-i-1)

print(max([max(ans1[i], 0) + max(ans2[-i-1], 0) for i in range(N-1)]))

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
for i in range(n):
  l[i]=[l[i][0],l[i][1],(l[i][0]+l[i][1])/2]

l=sorted(l,key=itemgetter(2))
L=[]
R=[]
for i in range(n):
  L.append(l[i][0])
for i in range(n):
  R.append(l[i][1])
L1=1;R1=10**9
L2=1;R2=10**9
list=[]
list2=[]
for i in range(n-1):
  L1=max(L1,l[i][0])
  R1=min(R1,l[i][1])
  list.append(R1-L1+1)
for i in range(n-1,0,-1):
  L2=max(L2,l[i][0])
  R2=min(R2,l[i][1])
  list2.append(R2-L2+1)

list2.reverse()
ans=[]
for i in range(n-1):
  ans.append(list[i]+list2[i])
print(max(ans))

Submission status: Wrong Answer

Solution code:
n=int(input())
lr=[[int(i) for i in input().split()] for j in range(n)]
lr=sorted(lr)
li_test=[]

for x,y in lr:
    li_test.append(y)

li=[li_test[0]]
a=li_test[0]
for i in range(1,n):
    a=min(li_test[i],a)
    li.append(a)

li_test=li_test[::-1]
li2=[li_test[0]]
a=li_test[0]
for i in range(1,n):
    a=min(li_test[i],a)
    li2.append(a)
li2=li2[::-1]
    
ans=0
maxi=lr[-1][0]
for i in range(n-1):
    one = max(0,li[i]-lr[i][0]+1)
    two = max(0,li2[i+1]-maxi+1)
    ans=max(ans,one+two)
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])) + 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(0, ra-la+1) + max(0, rb-lb+1)
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],)
ans=0
mini1=secondlist[0][0]
mini2=secondlist2[0][0]
max1=secondlist[0][1]
max2=secondlist2[0][1]
#min1,max1,で最初の試合の時の人数を抑える
#min2,max2,で次の試合の時の人数を抑える

#secondlist.append(10**10,10**10)
anslist1=[0 for i in range(n)]
for i in range(n):
    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):
    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)
print(max(Anslist))

Submission status: Wrong Answer

Solution code:

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

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

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

Submission status: Wrong Answer

Solution code:
n=int(input())
it=[]
for _ in range(n):
    it.append(list(map(int,input().split())))
it.sort()
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=-float("inf")
    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=-float("inf")
    bb[i]=so
ma=aa[0]+bb[1]
for i in range(1,n-1):
    ma=max(ma,aa[i]+bb[i+1])
print(ma)

Submission status: Wrong Answer

Solution code:
def calc(left_a, right_a, left_b, right_b, T):
    for left_t, right_t in T:
        los_a = max(0, left_t - left_a) + max(0, right_a - right_t)
        los_b = max(0, left_t - left_b) + max(0, right_b - right_t)

        if los_a <= los_b:
            left_a = max(left_a, left_t)
            right_a = min(right_a, right_t)
        else:
            left_b = max(left_b, left_t)
            right_b = min(right_b, right_t)

    return max(0, right_a - left_a + 1) + max(0, right_b - left_b + 1)


def f():
    N = int(input())
    W = [list(map(int, input().split())) for _ in range(N)]

    res = 0
    for k in range(1, N - 1):
        A = W[:k]
        B = W[k]
        T = W[k + 1:]

        left_a, right_a = A[0]
        for a in A:
            left_a = max(a[0], left_a)
            right_a = min(a[1], right_a)
            if left_a > right_a:
                left_a = right_a
                break

        left_b, right_b = B
        res = max(res, calc(left_a, right_a, left_b, right_b, T))
    print(res)


if __name__ == '__main__':
    f()

Submission status: Wrong Answer

Solution code:
from fractions import gcd
from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
import sys
from bisect import *
import itertools
import copy
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7


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

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def bisection(l,r,f):
    while(r-l>1):
        h=(l+r)//2
        if(f(h)<=f(h+1)):
            l=h
        else:
            r=h
    return r

def resolve():
    n=int(input())
    I=[tuple(map(int,input().split())) for _ in range(n)]
    I.sort(lambda x:x[1])
    S=[]
    def check(i):
        score=0
        l=0; r=INF
        for j in range(i): # 左側
            a,b=I[j]
            l=max(l,a)
            r=min(r,b)
        score+=max(r-l+1,0)
        l=0; r=INF
        for j in range(i,n): # 右側
            a,b=I[j]
            l=max(l,a)
            r=min(r,b)
        return score+max(r-l+1,0)

    i=bisection(1,n-1,check)
    print(check(i))
resolve()

Submission status: Wrong Answer

Solution code:

def sc(l,r):
    return max(0,r-l+1)

N = int(input())

al1 = 0
al2 = 0
ar1 = 0
ar2 = 0
nmax = 0

for i in range(N):

    L,R = map(int,input().split())

    if i == 0:
        al1 = L
        ar1 = R

    elif i == 1:
        al2 = L
        ar2 = R

    else:

        nmax = 0
        nmax = max(nmax, sc(max(al1,al2),min(ar1,ar2)) + sc(L,R) )
        nmax = max(nmax, sc(max(al1,L),min(ar1,R)) + sc(al2,ar2) )
        nmax = max(nmax, sc(max(al2,L),min(ar2,R)) + sc(al1,ar1) )
        #print (nmax)

        if nmax == (sc(max(al1,al2),min(ar1,ar2)) + sc(L,R)):

            nal1 = max(al1,al2)
            nar1 = min(ar1,ar2)
            nal2 = L
            nar2 = R
            #print ("a")

        elif nmax == (sc(max(al1,L),min(ar1,R)) + sc(al2,ar2) ):

            nal1 = max(al1,L)
            nar1 = min(ar1,R)
            nal2 = al2
            nar2 = ar2
            #print ("b")

        else:

            nal1 = max(al2,L)
            nar1 = min(ar2,R)
            nal2 = al1
            nar2 = ar1
            #print ("c")

        al1 = nal1
        al2 = nal2
        ar1 = nar1
        ar2 = nar2

    #print (al1,ar1,al2,ar2)

print (sc(al1,ar1) + sc(al2,ar2))

Submission status: Wrong Answer

Solution code:
n = int(input())
dif = [list(map(int,input().split())) for _ in range(n)]
l_min = max(dif, key = lambda x:x[1]-x[0])
dif.remove(l_min)
r_max = max(dif, key = lambda x:x[1]-x[0])
dif.remove(r_max)

a_l = l_min[0]
a_r = l_min[1]
b_l = r_max[0]
b_r = r_max[1]
def get_dif_score(l,r,new_l,new_r):
    tmp_score = r-l+1
    l = max(l, new_l)
    r = min(r, new_r)
    return tmp_score-max(r-l+1, 0), l, r

sub_dif = []
while len(dif) != 0:
    for i in range(len(dif)):
        score_dif_a, tmp_a_l, tmp_a_r = get_dif_score(a_l, a_r, dif[i][0], dif[i][1])
        score_dif_b, tmp_b_l, tmp_b_r = get_dif_score(b_l, b_r, dif[i][0], dif[i][1])
        if score_dif_a > score_dif_b:
            b_l = tmp_b_l
            b_r = tmp_b_r
        elif score_dif_a < score_dif_b:
            a_l = tmp_a_l
            a_r = tmp_a_r
        else:
            sub_dif.append(dif[i])
    dif = sub_dif
    sub_dif = []

# print(a_l, a_r, b_l, b_r, sub_dif)
print(max(a_r-a_l+1, 0)+max(b_r-b_l+1, 0))

Submission status: Wrong Answer

Solution code:

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

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

Lmax = Lsorted[0]
Rmin = Rsorted[0]
if Lmax[0]==Rmin[0] and Lmax[1]==Rmin[1]:
    LRdif = [LR[i][1]-LR[i][0]+1 for i in range(N)]
    LRdif.sort()
    print(Lmax[1]-Lmax[0]+1+LRdif[-1])
else:
#    M1 = Lmax[1]
#    M2 = Rmin[0]
#    for l,r in LR:
#        if r-Lmax[0] > Rmin[1]-l:
#            M1 = max(min(r,M1),Lmax[0]-1)
#        else:
#            M2 = min(max(l,M2),Rmin[1]+1)
#    print(M1-Lmax[0]+1 + Rmin[1]-M2+1)
    maxL = Rmin[0]
    maxscore = -10**27
    for i in range(1,N):
        nowminR = min(Rsorted[i][1],Lmax[1])
        maxscore =max(maxscore, max(nowminR-Lmax[0]+1,0) + max(Rmin[1]-maxL+1,0))
        maxL = max(Rsorted[i][0],maxL)
    print(maxscore)

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(max(0, r-l+1))
    
    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(max(0, r-l+1))
        

    ans = 0
    for i in range(N-1):
        ans = max(ans, lc[i] + rc[N-1-1-i])
    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:
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]

def honya(LR):
  l = LR[-1][0]
  r = LR[-1][1]
  D = [0] * N
  for i in range(N - 1, -1, -1):
    l = max(l, LR[i][0])
    r = min(r, LR[i][1])
    D[i] = max(0, r - l + 1)

  l = LR[0][0]
  r = LR[0][1]
  ans = 0
  for i in range(N - 1):
    r = min(r, LR[i][1])
    ans = max(ans, max(r - l + 1, 0) + D[i + 1])

  return ans

LR.sort(reverse = True)
#for i in range(N):
#  print(LR[i], LR[i][1] - LR[i][0])
  
ans = honya(LR)

R = 0
for i in range(N):
  R = max(R, LR[i][1])
for i in range(N):
  LR[i][0], LR[i][1] = R - LR[i][1], R - LR[i][0]
  
LR.sort(reverse = True)
ans = max(ans, honya(LR))

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], reverse=True)
    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(max(0, r-l+1))
    
    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(max(0, r-l+1))
        

    ans = 0
    for i in range(N-1):
        ans = max(ans, lc[i] + rc[N-1-1-i])
    return ans


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


if __name__ == '__main__':
    main()