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

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
lr = [LI() + [i] for i in range(n)]
x = sorted(lr, reverse=1)
L_max,R_,idx1 = x[0]
x = sorted(lr, key = itemgetter(1))
L_, R_min,idx2 = x[0]
tmp = 0
for l,r,i in lr:
    if i == idx1 or i == idx2:
        continue
    tmp = max(tmp,r-l+1)
ans1 = max(0,R_min - L_max+1) + tmp
lst = [[max(0,r-L_max+1),l,i] for l,r,i in lr]
lst.sort()
tmp1 = inf
ans2 = 0
for i in range(1,n):
    tmp1 = min(tmp1, max(0,R_min - lst[i-1][1]+1))
    tmp2 = lst[i][0]
    ans2 = max(ans2,tmp1+tmp2)
print(max(ans1,ans2))

Submission status: Accepted

Solution code:
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
lr = []
lmrer = BIG  # leftmost right end
lmrel = BIG
rmlel = -BIG # rightmost left end
rmler = -BIG
mx1 = -BIG
for i in range(n):
    l,r = inm()
    lr.append((l,r))
    #if r < lmrer:
    if r < lmrer or r==lmrer and l<lmrel:
        lmrer = r
        lmrel = l
        lmrei = i
    #if l > rmlel:
    if l > rmlel or l==rmlel and r>rmlel:
        rmlel = l
        rmler = r
        rmlei = i
    if r-l>mx1:
        mx1 = r-l

if n==2:
    print(lr[0][1]-lr[0][0]+1 + lr[1][1]-lr[1][0]+1)
    exit()

# longest vs all else
mx = max(0,lmrer-rmlel+1)+mx1+1
if lmrei==rmlei:
    print(mx)
    exit()

i1 = max(lmrei,rmlei)
i2 = min(lmrei,rmlei)
del lr[i1]
del lr[i2]
lr.sort()

rminr = [0]*(n-2)
rminr[n-3] = lr[n-3][1]
for i in range(n-4,-1,-1):
    rminr[i] = min(rminr[i+1],lr[i][1])

# lmre vs all else
len1 = lmrer-lmrel+1
len2 = rminr[0]-rmlel+1
mx = max(mx, len1+len2)

for i in range(n-3):
    len1 = lmrer-max(lmrel,lr[i][0])+1
    len2 = min(rmler,rminr[i+1])-rmlel+1
    mx = max(mx,len1+len2)

# rmle vs all else
len1 = lmrer-max(lmrel,lr[n-3][0])+1
len2 = rmler-rmlel+1
mx = max(mx,len1+len2)

print(mx)

Submission status: Accepted

Solution code:
N = int(input())
LR = [[0, 0] for i in range(N)]
p = q = -1
Lp = 0
Rq = 10**9 + 1
w_max = 0
for i in range(N):
  L, R = map(int, input().split())
  if L > Lp:
    Lp = L
    p = i
  if R < Rq:
    Rq = R
    q = i
  w_max = max(w_max, R-L+1)
  LR[i] = [L, R]


# 問題pと問題qを同じコンテストで実施する場合
ans = w_max + max(Rq-Lp+1, 0)
if p == q:
  print(ans)
  quit()

# 問題pと問題qを別々のコンテストで実施する場合
ab = []
wp = LR[p][1] - Lp + 1
wq = Rq - LR[q][0] + 1
for i in range(N):
  if i==p or i==q:
    continue
  ab.append([
    min(wp, max(LR[i][1]-Lp+1, 0)), -min(wq, max(Rq-LR[i][0]+1, 0))
  ])

# aの昇順(タイブレークはbの降順)に並べる
ab.sort()
ab.append([wp, 0])
b_min = wq
for a, b in ab:
  ans = max(ans, a+b_min)
  b_min = min(b_min, -b)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
maxl = 1
minr = 10**9+1
maxdis = 0
for i in range(N):
    if maxl < LR[i][0]:
        maxl = LR[i][0]
    if minr > LR[i][1]:
        minr = LR[i][1]
    if LR[i][1] - LR[i][0] > maxdis:
        maxdis = LR[i][1] - LR[i][0]

res = maxdis+1 + max(0, minr - maxl+1)

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

minb = 10**9+5
for i in range(N-1, -1, -1):
    minb = min(minb, max(0, LR[i][1]-maxl+1))
    LR[i].append(minb)
for i in range(N-1):
    res = max(res, max(0, minr - LR[i][0]+1)+LR[i+1][2])
print(res)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
a = [list(map(int, input().split())) for _ in range(N)]
for i in range(N): a[i][1] += 1
a.sort()
ls = [x[0] for x in a]
rs = [x[1] for x in a]

class SegTree:
  def segfunc(self, x, y):
    return min(x, y) #ここ判定関数（ただし結合則があるもの）
  def __init__(self, n, ide_ele, init_val):
    #####単位元######
    self.ide_ele = ide_ele
    #num:n以上の最小の2のべき乗
    self.num = 2 ** (n - 1).bit_length()
    self.seg = [self.ide_ele] * 2 * self.num
    #set_val
    for i in range(n):
      self.seg[i + self.num - 1] = init_val[i]    
    #built
    for i in range(self.num - 2, -1, -1) :
      self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2]) 
  def update(self, k, x):
    k += self.num - 1
    self.seg[k] = x
    while k + 1:
      k = (k - 1) // 2
      self.seg[k] = self.segfunc(self.seg[k * 2 + 1], self.seg[k * 2 + 2]) 
  def query(self, p, q):
    if q <= p:
      return self.ide_ele
    p += self.num - 1
    q += self.num - 2
    res = self.ide_ele
    while q - p > 1:
      if p & 1 == 0:
        res = self.segfunc(res, self.seg[p])
      if q & 1 == 1:
        res = self.segfunc(res, self.seg[q])
        q -= 1
      p = p // 2
      q = (q - 1) // 2
    if p == q:
      res = self.segfunc(res, self.seg[p])
    else:
      res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
    return res
class Seg2ree:
  def segfunc(self, x, y):
    return max(x, y) #ここ判定関数（ただし結合則があるもの）
  def __init__(self, n, ide_ele, init_val):
    #####単位元######
    self.ide_ele = ide_ele
    #num:n以上の最小の2のべき乗
    self.num = 2 ** (n - 1).bit_length()
    self.seg = [self.ide_ele] * 2 * self.num
    #set_val
    for i in range(n):
      self.seg[i + self.num - 1] = init_val[i]    
    #built
    for i in range(self.num - 2, -1, -1) :
      self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2]) 
  def update(self, k, x):
    k += self.num - 1
    self.seg[k] = x
    while k + 1:
      k = (k - 1) // 2
      self.seg[k] = self.segfunc(self.seg[k * 2 + 1], self.seg[k * 2 + 2]) 
  def query(self, p, q):
    if q <= p:
      return self.ide_ele
    p += self.num - 1
    q += self.num - 2
    res = self.ide_ele
    while q - p > 1:
      if p & 1 == 0:
        res = self.segfunc(res, self.seg[p])
      if q & 1 == 1:
        res = self.segfunc(res, self.seg[q])
        q -= 1
      p = p // 2
      q = (q - 1) // 2
    if p == q:
      res = self.segfunc(res, self.seg[p])
    else:
      res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
    return res
res = 0
segls = Seg2ree(N, 0, ls)
segrs = SegTree(N, 10 ** 10, rs)
#print(a)
for i in range(N - 1):
  l1 = segls.query(0, i)
  l2 = segls.query(i + 1, N)
  r1 = segrs.query(0, i)
  r2 = segrs.query(i + 1, N)
  if l1 == 0: l1 = 10 ** 10
  if r1 > 10 ** 9: r1 = a[i][1]
  t = a[i][1] - a[i][0] + max(0, min(r1, r2) - l2)
  t = max(t, max(0, r1 - a[i][0]) + r2 - l2)
  #print(i, t, l1, l2, r1, r2)
  res = max(res, t)
print(res)

Submission status: Accepted

Solution code:
from bisect import *
from collections import *
from fractions import gcd
from math import factorial
from itertools import *
from heapq import *



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

value=max([R-L for L,R in LR])
#LR=sorted(LR,key=lambda x:x[1])
LR=sorted(LR,key=lambda x:x[0]*10**9+x[1])
a=2*(10**9)
minRlst=[a for i in range(N)]
minRlst[-1]=LR[-1][1]
maxLlst=[0 for i in range(N)]
maxLlst[0]=LR[0][0]
for i in range(N-2,-1,-1):
    minRlst[i]=min(minRlst[i+1],LR[i][1])
for i in range(1,N):
    maxLlst[i]=max(minRlst[i-1],LR[i][0])
L1,R1=LR[0]
L2,R2=LR[-1][0],minRlst[1]
maxR=min([R for L,R in LR])
for i in range(0,N-1):
    L,R=LR[i]
    a=max(R-L,0)
    b=max(maxR-LR[-1][0],0)
    value=max(value,a+b)
    L1=L
    R1=min(R1,R)
    R2=minRlst[i+1]
    a=max(R1-L1,0)
    b=max(R2-L2,0)
    value=max(value,a+b)
print(value)

Submission status: Accepted

Solution code:
from itertools import accumulate
from operator import add
N = int(input())
LR = [tuple(map(int, input().split())) for _ in range(N)]
LR.sort()
f = lambda lr1, lr2: (max(lr1[0], lr2[0]), min(lr1[1], lr2[1]))
g = lambda lr: max(0, lr[1]-lr[0]+1)
A = list(map(g, accumulate(LR, f)))
B = list(map(g, accumulate(LR[::-1], f)))[-2::-1]
res = max(max(map(g, LR)) + A[-1], max(map(add, A, B)))
print(res)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

N = I()
L,R = Line(N,2)

l = max(L)
li = L.index(l)
r = min(R)
ri = R.index(r)
ans = max(r-l+1,0) + max([0 if (i==li or i==ri) else R[i]-L[i]+1 for i in range(N)])
if li==ri:
    print(ans)
    exit()

x = []
for i in range(N):
    if i==li or i==ri:
        continue
    else:
        x1 = max(R[i]-l+1, 0)
        x2 = max(r-L[i]+1, 0)
        x.append((x1,x2))

x.sort(key=lambda s:(-s[0],s[1]))

amin = R[li]-l+1
bmin = r-L[ri]+1
one = [amin]
two = [bmin]

for x0 in x:
    amin = min(amin,x0[0])
    one.append(amin)
for x0 in x[::-1]:
    bmin = min(bmin,x0[1])
    two.append(bmin)

two = list(reversed(two))
for i in range(len(one)):
    temp = one[i]+two[i]
    if temp>ans:
        ans = temp

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

maxLR = 10**9

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

LRs.sort()

accMinRs = [LRs[0][1]]
for L, R in LRs[1:]:
    accMinRs.append(min(accMinRs[-1], R))

accMinRRevs = [LRs[-1][1]]
for L, R in reversed(LRs[:-1]):
    accMinRRevs.append(min(accMinRRevs[-1], R))
accMinRRevs.reverse()

L2 = LRs[-1][0]
ans = 0
for x in range(N-1):
    L1, R1 = LRs[x]
    L0 = LRs[x-1][0] if x > 0 else 0
    R0 = accMinRs[x] if x > 0 else maxLR
    R2 = accMinRRevs[x+1]
    score1 = max(0, min(R0, R1)-max(L0, L1)+1) + max(0, R2-L2+1)
    score2 = max(0, R1-L1+1) + max(0, min(R0, R2)-max(L0, L2)+1)
    ans = max(ans, score1, score2)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def solve():
    N = int(input())
    LRs = []
    Ls, Rs = [], []
    for _ in range(N):
        L, R = map(int, input().split())
        LRs.append((L, R))
        Ls.append(L)
        Rs.append(R)

    Ls.sort(reverse=True)
    Rs.sort()

    maxL, maxL2 = Ls[:2]
    minR, minR2 = Rs[:2]

    # 1個にする要素を全探索
    ans = 0
    for L, R in LRs:
        num = R-L+1
        A, B = maxL, minR
        if L == maxL:
            A = maxL2
        if R == minR:
            B = minR2
        num += max(0, B-A+1)
        ans = max(ans, num)

    # 区切りを全探索
    LRs.sort(key=lambda x: x[0])

    minR = LRs[0][1]
    accMinRs = [minR]
    for L, R in LRs[1:]:
        minR = min(minR, R)
        accMinRs.append(minR)
    minR = LRs[-1][1]
    accMinRRevs = [minR]
    for L, R in reversed(LRs[:-1]):
        minR = min(minR, R)
        accMinRRevs.append(minR)
    accMinRRevs = accMinRRevs[::-1]

    for i in range(N-1):
        num = max(0, accMinRs[i] - LRs[i][0] + 1)
        num += max(0, accMinRRevs[i+1] - LRs[-1][0] + 1)
        ans = max(ans, num)

    # 区切りを全探索
    LRs.sort(key=lambda x: x[1])

    maxL = LRs[0][0]
    accMaxLs = [maxL]
    for L, R in LRs[1:]:
        maxL = max(maxL, L)
        accMaxLs.append(maxL)
    maxL = LRs[-1][0]
    accMaxLRevs = [maxL]
    for L, R in reversed(LRs[:-1]):
        maxL = max(maxL, L)
        accMaxLRevs.append(maxL)
    accMaxLRevs = accMaxLRevs[::-1]

    for i in range(N-1):
        num = max(0, LRs[0][1] - accMaxLs[i] + 1)
        num += max(0, LRs[i+1][1] - accMaxLRevs[i+1] + 1)
        ans = max(ans, num)

    print(ans)


solve()

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))  # applies to only numbers
rs = lambda: stdin.readline().rstrip()  # ignores trailing space

N = ri()
L = []
R = []
for _ in range(N):
    l, r = rl()
    L.append(l)
    R.append(r)

max_l = max(L)
min_R = min(R)
ab = [(max(0, r - max_l + 1), max(0, min_R - l + 1)) for l, r in zip(L, R)]
ab.sort()
answer = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_R - max_l + 1)
mi = float('inf')

for i in range(N-1):
    mi = min(mi, ab[i][1])
    answer = max(answer, mi + ab[i+1][0])

print(answer)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))  # applies to only numbers
rs = lambda: stdin.readline().rstrip()  # ignores trailing space

N = ri()
L = []
R = []

for _ in range(N):
    l, r = rl()
    L.append(l)
    R.append(r)

max_l = max(L)
min_r = min(R)
ab = [(max(0, r - max_l + 1), max(0, min_r - l + 1)) for l, r in zip(L, R)]
ab.sort()
mi = float('inf')
answer = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)
for i in range(N - 1):
    mi = min(mi, ab[i][1])
    # miは第１グループの人数
    answer = max(answer, mi + ab[i + 1][0])
print(answer)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    lr = [list(map(int, input().split())) for _ in [0] * n]
    lr.sort(key=lambda x: (x[0], x[1]))
    min_r = [0] * n
    min_r[0] = lr[0][1]
    min_l = [0] * n
    min_l[n-1] = lr[n-1][1]
    for i in range(1,n):
        min_r[i] = min(min_r[i - 1], lr[i][1])
    for i in range(n-2,-1,-1):
        min_l[i] = min(min_l[i + 1], lr[i][1])
    ans = max([max(min_r[i] - lr[i][0] + 1, 0) + max(min_l[i + 1] - lr[n - 1][0] + 1, 0) for i in range(n - 1)])
    l,r,w=0,10**9+1,0
    for i in range(n):
        l = max(l, lr[i][0])
        r = min(r, lr[i][1])
        w = max(w, lr[i][1] - lr[i][0]+1)
    ans = max(ans, max(r - l + 1, 0) + w)
    print(ans)
main()

Submission status: Accepted

Solution code:
def main():
  n,*t=map(int,open(0).read().split())
  (x,y),*t,(a,b)=sorted(zip(*[iter(t)]*2))
  r_min=[b]
  l_max=[a]
  for l,r in t[::-1]:
    r_min+=min(r_min[-1],r),
    l_max+=max(l_max[-1],l),
  m=max(0,y-x+1)+max(0,r_min.pop()-l_max.pop()+1)
  for l,r in t:
    i=r_min.pop()
    j=l_max.pop()
    v=min(y,r)
    w=max(x,l)
    m=max(m,max(0,i-j+1)+max(0,v-w+1),max(0,min(i,y)-max(j,x)+1)+max(0,r-l+1))
    y,x=v,w
  m=max(m,max(0,b-a+1)+max(0,y-x+1))
  print(m)
main()

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    ranges = []
    ans = 0
    for i in range(n):
        l, r = map(int, input().split())
        ranges.append((l, r))
        ans = max(ans, r - l + 1)
    min_ri = (10 ** 9 + 1, -1)
    max_li = (-1, -1)
    for i, (l, r) in enumerate(ranges):
        min_ri = min(min_ri, (r, i))
        max_li = max(max_li, (l, i))
    ri = min_ri[1]
    li = max_li[1]
    subranges = [ranges[i] for i in range(n) if i != ri and i != li]
    for r in subranges:
        ans = max(ans, min_ri[0] - max_li[0] + r[1] - r[0] + 2)
    if ri != li:
        lens = []
        for l, r in subranges:
            lens.append((max(0, r - max_li[0] + 1), max(0, min_ri[0] - l + 1)))
        lens.sort(key=lambda t: (t[0], -t[1]))
        m = len(subranges)
        fs = [ranges[li][1] - ranges[li][0] + 1] * (m + 1)
        ss = [ranges[ri][1] - ranges[ri][0] + 1] * (m + 1)
        for i in range(m):
            ss[i + 1] = min(ss[i], lens[i][1])
        for i in range(m, 0, -1):
            fs[i - 1] = min(fs[i], lens[i - 1][0])
        for i in range(m + 1):
            ans = max(ans, fs[i] + ss[i])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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-1):
    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,0,-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],ans)

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

ans2=0
for i in range(n):
    l,r=lr[i]
    rr=min(lr2[i][1],lr3[i][1])
    ll=max(lr2[i][0],lr3[i][0])
    d=max(0,rr-ll+1)
    ans2=max(ans2,r-l+1+d)


ans=max(ans,ans2)



print(ans)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
  N, *LR = map(int, stdin.buffer.read().split())
  L, R = LR[::2], LR[1::2]#偶数個目、奇数個目を取ってきている
  max_l = max(L)
  min_r = min(R)
  ab = [(max(0, r - max_l + 1), max(0, min_r - l + 1)) for l, r in zip(L, R)]
  #各RとLの上限との間に何人いるか、各LとRの下限との間に何人いるか全員調査
  #abは各LRが、L上限、R下限の境界をどの程度超えているかのリスト
  ab.sort()
  mi = float("inf")
  ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, min_r - max_l + 1)
  #maはLRの間に入る人数の最大値＋共通ライン（簡単に考えられる最大の分け方）
  for i in range(N - 1):
    mi = min(mi, ab[i][1])
    #過去に調査したR下限を超える部分下の部分のうち最小のもの（第1グループ）
    ma = max(ma, mi + ab[i + 1][0])
    #miとL上限を超える上の部分（ソートしているので次の候補が一番最小）の和とmaを比べている。
  print(ma)
    
main()

Submission status: Accepted

Solution code:
# coding: utf-8


def solve(*args: str) -> str:
    n = int(args[0])
    LR = [tuple(map(int, a.split())) for a in args[1:]]

    ret = 0

    # lp, rq = max(L), min(R)
    # d_max = max(1+r-l for l, r in LR)
    lp, rq = 0, 1+10**9
    d_max = 0
    for l, r in LR:
        lp, rq = max(lp, l), min(rq, r)
        d_max = max(d_max, 1+r-l)

    ret = max(0, 1+rq-lp) + d_max

    AB = [[max(0, 1+r-lp), max(0, 1+rq-l)] for l, r in LR]
    AB.sort(key=lambda x: (x[0], -x[1]))
    A, B = map(list, zip(*AB))

    # for i in range(1, n):
    #     ret = max(ret, min(A[i:]) + min(B[:i]))
    b_min = 1+10**9
    for i in range(n-1):
        b_min = min(b_min, B[i])
        ret = max(ret, b_min + A[i+1])

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

Solution code:
# coding: utf-8


def solve(*args: str) -> str:
    n = int(args[0])
    LR = [tuple(map(int, a.split())) for a in args[1:]]
    L, R = zip(*LR)

    ret = 0

    # lp, rq = max(L), min(R)
    lp, rq = 0, 1+10**9
    for l, r in LR:
        lp, rq = max(lp, l), min(rq, r)

    ret = max(0, 1+rq-lp) + max(0, max(1+r-l for l, r in LR))

    AB = [[max(0, 1+r-lp), max(0, 1+rq-l)] for l, r in LR]
    AB.sort(key=lambda x: (x[0], -x[1]))
    A, B = map(list, zip(*AB))

    # for i in range(1, n):
    #     ret = max(ret, min(A[i:]) + min(B[:i]))
    b_min = 1+10**9
    for i in range(n-1):
        b_min = min(b_min, B[i])
        ret = max(ret, b_min + A[i+1])

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

Solution code:
# coding: utf-8
import numpy as np


def solve(*args: str) -> str:
    n = int(args[0])
    LR = [tuple(map(int, a.split())) for a in args[1:]]
    L, R = zip(*LR)

    ret = 0

    p, q = np.argmax(L), np.argmin(R)
    lp, rq = L[p], R[q]

    ret = max(0, 1+rq-lp) + max(0, max(1+r-l for l, r in LR))

    AB = [[max(0, 1+r-lp), max(0, 1+rq-l)] for l, r in LR]
    AB.sort(key=lambda x: (x[0], -x[1]))
    A, B = map(list, zip(*AB))

    # for i in range(1, n):
    #     ret = max(ret, min(A[i:]) + min(B[:i]))
    b_min = 1+10**9
    for i in range(n-1):
        b_min = min(b_min, B[i])
        ret = max(ret, b_min + A[i+1])

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:


from operator import itemgetter


# In[2]:


N = int(input())
LR = [[0, 0] for _ in range(N)]
for i in range(N):
    LR[i][0], LR[i][1] = map(int, input().split())


# In[3]:


maxL = 0
minR = 10 ** 9
for i in range(N):
    maxL = max(maxL, LR[i][0])
    minR = min(minR, LR[i][1])


# In[4]:


ans = 0


# In[5]:


def func(list):
    ret = []
    left = list[0][0]
    right = list[0][1]
    ret.append(right - left + 1)
    for i in range(1, len(list)):
        left = max(left, list[i][0])
        right = min(right, list[i][1])
        ret.append(right - left + 1)
    return ret


# In[6]:


LR.sort(key=itemgetter(1))
LR.sort(key=itemgetter(0))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[7]:


m = 0
for i in range(N - 1):
    m = max(m, list1[i] + list2[N - i - 2])
ans = max(ans, m)


# In[8]:


LR.sort(key=itemgetter(1), reverse=True)
LR.sort(key=itemgetter(0))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[9]:


m = 0
for i in range(N - 1):
    m = max(m, list1[i] + list2[N - i - 2])
ans = max(ans, m)


# In[10]:


LR.sort(key=itemgetter(0))
LR.sort(key=itemgetter(1))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[11]:


m = 0
for i in range(N - 1):
    m = max(m, list1[i] + list2[N - i - 2])
ans = max(ans, m)


# In[12]:


LR.sort(key=itemgetter(0), reverse=True)
LR.sort(key=itemgetter(1))
list1 = func(LR)
LR.reverse()
list2 = func(LR)


# In[13]:


m = 0
for i in range(N):
    m = max(m, LR[i][1] - LR[i][0] + 1)

if minR >= maxL:
    ans = max(ans, m + minR - maxL + 1)
else:
    ans = max(ans, m)


# In[14]:


print(ans)


# In[ ]:

Submission status: Accepted

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

for i in range(N) :
    LR[i][1] += 1

a, b = 0, 0
la, ra = 0, float('inf')
lb, rb = -float('inf'), 0

for i, (l, r) in enumerate(LR) :
    if r < ra or (r == ra and l < la) :
        la, ra = l, r
        a = i
        
    if l > lb or (l == rb and r > rb) :
        lb, rb = l, r
        b = i

ret = 0

Md = 0
for i, (l, r) in enumerate(LR) :
    if i != a and i != b :
        Md = max(Md, r - l)
ret = max(ret, max(0, ra - lb) + Md)

LR.sort(key=lambda x: x[1])
LR.sort()
dpl = [0] * N
dpr = [0] * N

dpl[0] = max(la, LR[0][0])
dpr[N-1] = min(rb, LR[N-1][1])

for i in range(1, N) :
    dpl[i] = max(dpl[i-1], LR[i][0])
    dpr[N-1-i] = min(dpr[N-i], LR[N-1-i][1])
    
for i in range(N - 1) :
    ret = max(ret, max(0, ra - dpl[i]) + max(0, dpr[i + 1] - lb))
    
print(ret)

Submission status: Accepted

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

left_sort = sorted(lr, key=lambda tup: tup[0])     # O(nlogn)

joy_from_left = [0]
min_right = float('inf')
max_left = 0
for l, r in left_sort:     # O(n)
    min_right = min(r, min_right)
    max_left = max(l, max_left)
    joy_from_left.append(max(0, min_right - max_left + 1))

joy_from_right = [0]
min_right = float('inf')
max_left = 0
for l, r in reversed(left_sort):       # O(n)
    min_right = min(r, min_right)
    max_left = max(l, max_left)
    joy_from_right.append(max(0, min_right - max_left + 1))

joy_pair = max(l+r for l, r in zip(joy_from_left, reversed(joy_from_right)))        # O(n)


longest = max(left_sort, key=lambda tup: tup[1]-tup[0])     # O(n)
longest_joy = longest[1] - longest[0] + 1

removed = list(filter(lambda tup: tup!=longest, left_sort))     # O(n)
min_right = min(r for _, r in removed)
max_left = max(l for l, _ in removed)
except_longest_joy = max(0, min_right - max_left + 1)

print(max(joy_pair, longest_joy + except_longest_joy))    # O(nlogn) + O(n) = O(nlogn)

Submission status: Accepted

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)
L.sort()
R.sort()
ans = 0
for l, r in LR:
    m = L[-1]
    M = R[0]
    if l == m:
        m = L[-2]
    if M == r:
        M = R[1]
    ans = max(max(0, M-m+1)+r-l+1, ans)
LR.sort()
tmp = [LR[-1]]
Rmin = LR[-1][1]
for i in range(N-1)[::-1]:
    if LR[i][1]<=Rmin:
        tmp.append(LR[i])
        Rmin = LR[i][1]
LR = tmp[::-1]
rmin = LR[0][1]
lmax = LR[-1][0]
for i in range(len(LR)-1):
    l0, r0 = LR[i]
    l1, r1 = LR[i+1]
    res1 = max(0, rmin-l0+1)
    res2 = max(0, r1-lmax+1)
    ans = max(ans, res1+res2)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
raw = []
for _ in range(n):
  raw.append(list(map(int,input().split())))
raw.sort(key= lambda x: x[1])
EF = []
for i in range(n):
  EF.append(raw[i][1])
SL1 = [raw[0][0]]
for i in range(1,n):
  SL1.append(max(SL1[-1],raw[i][0]))
SL2 = [raw[-1][0]]
for i in range(1,n):
  SL2.append(max(SL2[-1],raw[n-i-1][0]))
SL2.reverse()
#print(EF)
#print(SL1)
#print(SL2)
can = []
for i in range(n-1):
  tmp = max(EF[0]-SL1[i]+1,0) + max(EF[i+1]-SL2[i+1]+1,0)
  can.append(tmp)
#print(can)
ans1 = max(can)
xlen = []
xl = []
xr = []
for i in range(n):
  xlen.append(raw[i][1] - raw[i][0] + 1)
  xl.append(raw[i][0])
  xr.append(raw[i][1])
#print(max(xl))
ans2 = max(xlen) + max(0,min(xr)-max(xl)+1)
print(max(ans1,ans2))

Submission status: Accepted

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

L,R = zip(*LRs)
Lp = max(L)
Rq = min(R)

A = [max(0, r-Lp+1) for r in R]
B = [max(Rq-l+1, 0) for l in L]
AB = sorted(zip(A,B))
A2,B2 = zip(*AB)

mlr = max(r-l for l,r in LRs) + 1
m = max(0, Rq - Lp + 1) + mlr
mt = B2[0]
for i,a in enumerate(A2[0:-1:]):
    mt = min(mt, B2[i])
    ms = A2[i+1]
    m = max(m, ms+mt)

print(m)

Submission status: Accepted

Solution code:
def solve(N, LRs):
    from operator import itemgetter
    L = 0
    R = 1
    IND = 2

    LRs.sort(key=itemgetter(L))  # L昇順ソート
    LRs = tuple(LR + (ind,) for ind, LR in enumerate(LRs))

    min_r = min(LRs, key=itemgetter(R))  # R最小の区間 == 右端が一番左の区間
    max_l = max(LRs, key=itemgetter(L))  # L最大の区間 == 左端が一番右の区間

    ans = 0
    if min_r[IND] == max_l[IND]:
        # L最大とR最小の問題が一致する場合
        fixed = max(0, min_r[R] - max_l[L] + 1)
        max_ = max(0, max(x[R] - x[L] + 1 for x in LRs if x[IND] != max_l[IND]))
        ans = max(ans, fixed + max_)
    else:
        # L最大とR最小の問題が異なる場合

        # 両方の問題を同日実施する場合
        fixed = max(0, min_r[R] - max_l[L] + 1)
        max_ = max(0, max(x[R] - x[L] + 1 for x in LRs if x[IND] != max_l[IND]))
        ans = max(ans, fixed + max_)

        r_mins = []
        t = 10 ** 9 + 1
        for LR in reversed(LRs):
            if LR[IND] != min_r[IND]:
                t = min(t, LR[R])
            r_mins.append(t)
        r_mins.reverse()

        # 別日に実施する場合
        for x in LRs:
            # min_rと同日に実施する問題で、L最大の問題x
            if x[IND] == max_l[IND]:
                continue
            fixed = max(0, min_r[R] - x[L] + 1)
            r_ = r_mins[x[IND] + 1]
            opp = max(0, r_ - max_l[L] + 1)
            ans = max(ans, fixed + opp)

    return ans


if __name__ == '__main__':
    N = int(input())
    LRs = [tuple(map(int, input().split())) for _ in range(N)]
    print(solve(N, LRs))

# 残った区間
# <-->, <--->
# <>は、いずれかの区間の左右端なので、n通り**4ある
# 右端が一番左にあるような区間に注目すると
# どの区間と組み合わせても、右端は変わらない（emptyになることはある）
# 右端が一番左 / 左端が一番右 に注目する

# 例外 == 両者一致 == 含まれるケース
# <----->
#  <--->
#   <->    ... この区間を含むとこの区間だけになるので、最長区間とそれ以外(これを含む）に分ける

# 右端が一番左 / 左端が一番右 を同じ区間に入れる場合と違う区間に入れる場合に分ける
# 同じ区間に入れる場合は、例外同様、最長区間とその他に分ける

# 右端が一番左 / 左端が一番右 を別日に実施する場合、
# x---o (右端は固定）
# xに決めたとき、 o---y yを最長になるようにしたい
# x---o (右端は固定）
# <---            xより左に左端があるもの : 別グループ（左端が一番右の区間以下確定）に入れると、
#                                     区間長維持または減少なので、x----oと同じグループに入れて、別グループの長さを維持したい
#       <---     oより右に左端があるもの : 別グループに入れないとx---o区間を取るという決め方に反する

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

_n = int(input())
lrlist = [list(map(int, input().split())) for _ in range(_n)]
Lp, Rq = max(l for l, r in lrlist), min(r for l, r in lrlist)

st = sorted([(max(r - Lp + 1, 0), max(Rq - l + 1, 0)) for l, r in lrlist], key=lambda x: (x[0], -x[1]))
ans = max([r - l + 1 for l, r in lrlist]) + max(Rq - Lp + 1, 0)

min_b = 10 ** 9
for i in range(_n - 1):
    min_b = min(st[i][1], min_b)
    ans = max(ans, min_b + st[i + 1][0])

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, *LR = map(int, stdin.buffer.read().split())
    L, R = LR[::2], LR[1::2]

    Lp = max(L)
    Rq = min(R)

    AB = sorted((max(0, r - Lp + 1), -max(0, Rq - l + 1)) for l, r in zip(L, R))

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, Rq - Lp + 1)

    for i, (a, b) in enumerate(AB):
        if i:
            ma = max(ma, mi + a)
        mi = min(mi, -b)

    print(ma)


main()

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, *LR = map(int, stdin.buffer.read().split())
    L, R = LR[::2], LR[1::2]

    Lp = max(L)
    Rq = min(R)

    A, B = zip(*sorted((max(0, r - Lp + 1), -max(0, Rq - l + 1)) for l, r in zip(L, R)))

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, Rq - Lp + 1)

    for a, b in zip(A[1:], B):
        mi = min(mi, -b)
        ma = max(ma, mi + a)

    print(ma)


main()

Submission status: Accepted

Solution code:
N, *LR = map(int, open(0).read().split())
L, R = LR[::2], LR[1::2]

Lp = max(L)
Rq = min(R)

A, B = zip(*sorted((max(0, r - Lp + 1), -max(0, Rq - l + 1)) for l, r in zip(L, R)))

mi = float("inf")
ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, Rq - Lp + 1)

for a, b in zip(A[1:], B):
    mi = min(mi, -b)
    ma = max(ma, mi + a)

print(ma)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, *LR = map(int, stdin.buffer.read().split())
    L, R = LR[::2], LR[1::2]

    Lp = max(L)
    Rq = min(R)

    A = sorted(max(0, r - Lp + 1) for r in R)
    B = sorted(-max(0, Rq - l + 1) for l in L)

    mi = float("inf")
    ma = max(r - l + 1 for l, r in zip(L, R)) + max(0, Rq - Lp + 1)

    for a, b in zip(A[1:], B):
        mi = min(mi, -b)
        ma = max(ma, mi + a)

    print(ma)

main()