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 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 = Rsorted[i][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:
import sys
input = sys.stdin.readline

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

task.sort()
#print(task)
ans = 0

task_minmax = [None] * (N+1)
task_minmax[N] = [0, 10**9]
for i in range(N-1, -1, -1):
    task_minmax[i] = [max(task_minmax[i+1][0], task[i][0]), min(task_minmax[i+1][1], task[i][1])]

mini = 0
maxi = 10**9

#print(task_minmax)

for i in range(N-1):
    temp = 0
    if i != 0:
        ans = max(ans, max(0, min(maxi, task_minmax[i+1][1]) - max(mini, task_minmax[i+1][0]) + 1) + (task[i][1] - task[i][0]) + 1)

    mini = max(task[i][0], mini)
    maxi = min(task[i][1], maxi)

    temp += maxi - mini + 1
    temp += max(task_minmax[i+1][1] - task_minmax[i+1][0] + 1, 0)

    ans = max(temp, ans)

print(ans)

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 = []
for i,(l,r) in enumerate(LR):
    ls.append((l,i))
ls.sort()

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

r_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)
    r_ans.append(max(0, minr - maxl + 1))

r_ans.reverse()

ans = 0
for l,r in list(zip(l_ans, r_ans))[1:-1]:
    ans = max(ans, l+r)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
dif = [list(map(int,input().split())) for _ in range(n)]
l_min = min(dif, key = lambda x:x[0])
dif.remove(l_min)
r_max = max(dif, key = lambda x:x[1])
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:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
# input = sys.stdin.readline

n = int(input())
lr = []
for i in range(n):
    l, r = [int(item) for item in input().split()]
    lr.append((r-l+1, l, r))
lr.sort()
al = lr[0][1]; ar = lr[0][2]; anum = ar - al + 1
bl = lr[1][1]; br = lr[1][2]; bnum = br- bl + 1

for i in range(2, n):
    nl = lr[i][1]; nr = lr[i][2]
    # add new to a
    adda_l = max(al, nl)
    adda_r = min(ar, nr)
    adda_num = adda_r - adda_l + 1
    adda_ret = adda_num + bnum
    # add new to b
    addb_l = max(bl, nl)
    addb_r = min(br, nr)
    addb_num = addb_r - addb_l + 1
    addb_ret = addb_num + anum
    # create new
    create_l = max(al, bl)
    create_r = min(ar, br)
    create_num = create_r - create_l + 1
    cnum = nr - nl + 1
    create_ret = create_num + cnum

    if adda_ret >= addb_ret and adda_ret >= create_ret:
        al = adda_l
        ar = adda_r
        anum = adda_num
    elif addb_ret >= adda_ret and addb_ret >= create_ret:
        bl = addb_l
        br = addb_r
        bnum = addb_num
    else:
        al = create_l
        ar = create_r
        anum = create_num
        bl = nl
        br = nr
        bnum = cnum

print(anum + bnum)

Submission status: Wrong Answer

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

def myeval(arg):
    if arg[0] != None:
        L_tmp, R_tmp = arg[0]
        score = max(0, R_tmp - L_tmp + 1)
    else:
        score = 0
    if arg[1] != None:
        L_tmp, R_tmp = arg[1]
        score += max(0, R_tmp - L_tmp + 1)
    else:
        score += 0
    return score

ans = [None, None]
for i, (Li, Ri) in enumerate(LR):
    # print("#", ans, myeval(ans))
    # add left
    ans_l = list(ans)
    if ans_l[0] != None: L_tmp, R_tmp = ans_l[0]
    else: L_tmp, R_tmp = (0, 10 ** 9 + 7)
    ans_l[0] = (max(L_tmp, Li), min(R_tmp, Ri))
    # add right
    ans_r = list(ans)
    if ans_r[1] != None: L_tmp, R_tmp = ans_r[1]
    else: L_tmp, R_tmp = (0, 10 ** 9 + 7)
    ans_r[1] = (max(L_tmp, Li), min(R_tmp, Ri))
    # evaluate score
    score_l = myeval(ans_l)
    score_r = myeval(ans_r)
    # judge
    if score_l < score_r:
        ans = list(ans_r)
    else:
        ans = list(ans_l)
        
print(myeval(ans))

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

Submission status: Wrong Answer

Solution code:
import sys
from itertools import accumulate

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

lr_dict = {}
lr_list = []
for i, lr in enumerate(sorted(appeared_lr)):
    lr_dict[lr] = i
    lr_list.append(lr)

tasks.sort()
tasks_li = [lr_dict[l] for l, _ in tasks]
tasks_ri = [lr_dict[r] for _, r in tasks]
tasks_ri_acc_fwd = list(accumulate(tasks_ri, func=min))
tasks_ri_acc_bwd = list(reversed(list(accumulate(reversed(tasks_ri), func=min))))

right_max_l = lr_list[tasks_li[-1]]
score = 0
for i in range(1, n):
    left_max_l = lr_list[tasks_li[i - 1]]
    left_min_r = lr_list[tasks_ri_acc_fwd[i - 1]]
    right_min_r = lr_list[tasks_ri_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)
print(score)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
# input = sys.stdin.readline

n = int(input())
lr = []
for i in range(n):
    l, r = [int(item) for item in input().split()]
    lr.append((l, r))
lr.sort()
al = lr[0][0]; ar = lr[0][1]; anum = ar - al + 1
bl = lr[1][0]; br = lr[1][1]; bnum = br- bl + 1

for i in range(2, n):
    nl = lr[i][0]; nr = lr[i][1]
    # add new to a
    adda_l = max(al, nl)
    adda_r = min(ar, nr)
    adda_num = adda_r - adda_l + 1
    adda_ret = adda_num + bnum
    # add new to b
    addb_l = max(bl, nl)
    addb_r = min(br, nr)
    addb_num = addb_r - addb_l + 1
    addb_ret = addb_num + anum
    # create new
    create_l = max(al, bl)
    create_r = min(ar, br)
    create_num = create_r - create_l + 1
    cnum = nr - nl + 1
    create_ret = create_num + cnum

    if adda_ret >= addb_ret and adda_ret >= create_ret:
        al = adda_l
        ar = adda_r
        anum = adda_num
    elif addb_ret >= adda_ret and addb_ret >= create_ret:
        bl = addb_l
        br = addb_r
        bnum = addb_num
    else:
        al = create_l
        ar = create_r
        anum = create_num
        bl = nl
        br = nr
        bnum = cnum

print(anum + bnum)

Submission status: Wrong Answer

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])
    print(max([min_r[i] - lr[i][0] + min_l[i+1] - lr[n-1][0] for i in range(n-1)])+2)
main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
n=int(input())
lr=[list(map(int,input().split())) for _ in range(n)]
lr.sort(key=lambda x:x[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
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)
print(ans)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
l=sorted(l)
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])
a=max(ans)

l=sorted(l,key=itemgetter(1))
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])
b=max(ans)
print(max(a,b))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
# input = sys.stdin.readline

n = int(input())
lr = []
for i in range(n):
    l, r = [int(item) for item in input().split()]
    lr.append((l, r))
al = lr[0][0]; ar = lr[0][1]; anum = ar - al + 1
bl = lr[1][0]; br = lr[1][1]; bnum = br- bl + 1

for i in range(2, n):
    nl = lr[i][0]; nr = lr[i][1]
    # add new to a
    adda_l = max(al, nl)
    adda_r = min(ar, nr)
    adda_num = adda_r - adda_l + 1
    adda_ret = adda_num + bnum
    # add new to b
    addb_l = max(bl, nl)
    addb_r = min(br, nr)
    addb_num = addb_r - addb_l + 1
    addb_ret = addb_num + anum
    # create new
    create_l = max(al, bl)
    create_r = min(ar, br)
    create_num = create_r - create_l + 1
    cnum = nr - nl + 1
    create_ret = create_num + cnum

    if adda_ret >= addb_ret and adda_ret >= create_ret:
        al = adda_l
        ar = adda_r
        anum = adda_num
    elif addb_ret >= adda_ret and addb_ret >= create_ret:
        bl = addb_l
        br = addb_r
        bnum = addb_num
    else:
        al = create_l
        ar = create_r
        anum = create_num
        bl = nl
        br = nr
        bnum = cnum

print(anum + bnum)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
import bisect


def cross(a, b):
    l = max(a[0], b[0])
    r = min(a[1], b[1])
    if l <= r:
        return (l, r)
    else:
        return (-1, -2)
    
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
info = sorted(info, key = itemgetter(1))


l_ans = [(0, 10**9)]
for i in range(n):
    tmp = cross(l_ans[-1], info[i])
    l_ans.append(tmp)

r_ans = [(0, 10**9)]
for i in range(n)[::-1]:
    tmp = cross(r_ans[-1], info[i])
    r_ans.append(tmp)
r_ans = r_ans[::-1]

max_ans = 0
for i in range(1,n):
    ans = (l_ans[i][1] - l_ans[i][0]) + (r_ans[i][1] - r_ans[i][0]) + 2
    max_ans = max(ans, max_ans)
    
for i in range(n):
    ans = info[i][1] - info[i][0] + 1
    tmp = cross(l_ans[i], r_ans[i+1])
    ans += tmp[1] - tmp[0] + 1
    max_ans = max(ans, max_ans)

info = sorted(info)
l_ans = [(0, 10**9)]
for i in range(n):
    tmp = cross(l_ans[-1], info[i])
    l_ans.append(tmp)

r_ans = [(0, 10**9)]
for i in range(n)[::-1]:
    tmp = cross(r_ans[-1], info[i])
    r_ans.append(tmp)
r_ans = r_ans[::-1]

max_ans = 0
for i in range(1,n):
    ans = (l_ans[i][1] - l_ans[i][0]) + (r_ans[i][1] - r_ans[i][0]) + 2
    max_ans = max(ans, max_ans)
print(max_ans)

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+=r-l+1
        l=0; r=INF
        for j in range(i,n): # 右側
            a,b=I[j]
            l=max(l,a)
            r=min(r,b)
        return score+r-l+1

    i=bisection(1,n,check)
    if(i<n):
        print(check(i))
    else:
        print(check(n-1))
resolve()

Submission status: Wrong Answer

Solution code:
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
l.sort()
L=[]
R=[]
for i in range(n):
  L.append(l[i][0])
for i in range(n):
  R.append(l[i][1])
x=max(0,min(R)-max(L)+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())
data=[list(map(int,input().split())) for i in range(n)]
data.sort()
l,r=data[0]
lst=[0]*n
lst[0]=r-l+1
for i in range(1,n):
    a,b=data[i]
    l=a
    if b<r:
        r=b
    lst[i]=max(0,r-l+1)
li=[0]*n
l,r=data[n-1]
li[n-1]=r-l+1
for i in range(1,n):
    a,b=data[n-1-i]
    if b<r:
        r=b
    li[n-1-i]=max(0,r-l+1)
ans=0
for i in range(n):
    l,r=data[i]
    ans=max(ans,r-l+1)
for i in range(n-1):
    ans=max(ans,lst[i]+li[i+1])
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
dif = [list(map(int,input().split())) for _ in range(n)]
l_min = min(dif, key = lambda x:x[0])
dif.remove(l_min)
r_max = max(dif, key = lambda x:x[1])
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

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:
        a_l = tmp_a_l
        a_r = tmp_a_r
    else:
        b_l = tmp_b_l
        b_r = tmp_b_r
# print(a_l, a_r, b_l, b_r)
print(a_r-a_l+b_r-b_l+2)

Submission status: Wrong Answer

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

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

task.sort()
#print(task)
ans = 0

task_minmax = [None] * (N+1)
task_minmax[N] = [0, 10**9]
for i in range(N-1, -1, -1):
    task_minmax[i] = [max(task_minmax[i+1][0], task[i][0]), min(task_minmax[i+1][1], task[i][1])]


mini = 0
maxi = 10**9

for i in range(N-1):
    temp = 0
    mini = max(task[i][0], mini)
    maxi = min(task[i][1], maxi)

    temp += maxi - mini + 1
    temp += max(task_minmax[i+1][1] - task_minmax[i+1][0] + 1, 0)

    ans = max(temp, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
import bisect


def cross(a, b):
    l = max(a[0], b[0])
    r = min(a[1], b[1])
    if l < r:
        return (l, r)
    else:
        return (-1, -2)
    
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
info = sorted(info, key = itemgetter(1))


l_ans = [(0, 10**9)]
for i in range(n):
    tmp = cross(l_ans[-1], info[i])
    l_ans.append(tmp)

r_ans = [(0, 10**9)]
for i in range(n)[::-1]:
    tmp = cross(r_ans[-1], info[i])
    r_ans.append(tmp)
r_ans = r_ans[::-1]

max_ans = 0
for i in range(1,n):
    ans = (l_ans[i][1] - l_ans[i][0]) + (r_ans[i][1] - r_ans[i][0]) + 2
    max_ans = max(ans, max_ans)
    
for i in range(n):
    ans = info[i][1] - info[i][0] + 1
    tmp = cross(l_ans[i], r_ans[i+1])
    ans += tmp[1] - tmp[0] + 1
    max_ans = max(ans, max_ans)
print(ans)

Submission status: Wrong Answer

Solution code:
s = input()
l = [0 for i in range(len(s)+1)]
if s[0] == '<':
  cnt = 1
  for i in range(0, len(s)):
    if s[i] == '<':
      l[i+1] = max(cnt, l[i+1])
      cnt += 1
    else:
      break
if s[-1] == '>':
  cnt = 1
  for i in range(len(s)-1, -1, -1):
    if s[i] == '>':
      l[i] = max(cnt, l[i])
      cnt += 1
    else:
      break
for i in range(1, len(s)):
  if s[i-1:i+1] == '><':
    #左側検索
    cnt = 1
    for j in range(i-1, -1, -1):
      if s[j] == '>':
        l[j] = max(cnt, l[j])
        cnt += 1
      else:
        break
    #右側検索
    cnt = 1
    for j in range(i, len(s)):
      if s[j] == '<':
        l[j+1] = max(cnt, l[j])
        cnt += 1
      else:
        break
ans = sum(l)
print(ans)

Submission status: Wrong Answer

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

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

task.sort()
#print(task)
ans = 0
'''
task_minmax = [None] * (N+1)
task_minmax[N] = [0, 10**9]
for i in range(N-1, -1, -1):
    task_minmax[i] = [max(task_minmax[i+1][0], task[i][0]), min(task_minmax[i+1][1], task[i][1])]

print(task_minmax)
'''

for i in range(1, N):
    temp = 0
    mini = 0
    maxi = 10**9
    for j in range(i):
        mini = max(task[j][0], mini)
        maxi = min(task[j][1], maxi)

    temp += maxi - mini + 1

    mini = 0
    maxi = 10**9
    for j in range(i, N):
        mini = max(task[j][0], mini)
        maxi = min(task[j][1], maxi)
    temp += maxi - mini + 1

    ans = max(temp, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
import math
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


class SparseTable:
    """
    構築 O(NlogN)、クエリ O(1)
    """

    def __init__(self, values, fn):
        """
        :param list values:
        :param callable fn: 結合則を満たす冪等な関数。min、max など。add はだめ
        """
        self._values = values
        self._fn = fn

        # SparseTable を構築
        # self._table[i][p]: [i, i+2^p) に fn を適用した結果の値のインデックス
        self._table = self._build(values, fn)

        # self._msb[i]: 最上位ビット; どの p を見るべきか
        self._msb = [0] * (len(values) + 1)
        for i in range(2, len(values) + 1):
            self._msb[i] = self._msb[i >> 1] + 1

    @staticmethod
    def _build(values, fn):
        # AtCoder の PyPy 2.4.0 では math.log2 が使えない
        size = int(math.log(len(values), 2)) + 1

        st = [[0] * size for _ in range(len(values))]
        for i in range(len(values)):
            st[i][0] = i
        for p in range(1, size):
            for i in range(len(values)):
                q = min(i + (1 << (p - 1)), len(values) - 1)
                l = st[i][p - 1]
                r = st[q][p - 1]
                if values[l] == fn(values[l], values[r]):
                    st[i][p] = l
                else:
                    st[i][p] = r
        return st

    def get(self, a, b):
        """
        半開区間 [a, b) に fn を適用した結果
        :param int a:
        :param int b:
        """
        if b <= a:
            return None
        p = self._msb[b - a]
        return self._fn(
            self._values[self._table[a][p]],
            self._values[self._table[b - (1 << p)][p]]
        )


N = int(sys.stdin.readline())
LR = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]


def calc_score(lr):
    ma = IINF
    mi = 0
    for l, r in lr:
        ma = min(ma, r)
        mi = max(mi, l)
    return max(0, ma - mi + 1)


def test(N, LR):
    import numpy as np
    LR = np.array(LR, dtype=int)
    ret = 0
    for choice in itertools.product([True, False], repeat=N):
        if sum(choice) in [N, 0]:
            continue
        choice = np.array(choice)
        score = calc_score(LR[choice]) + calc_score(LR[~choice])
        ret = max(score, ret)
        print(score, choice)
    print(ret)
    return ret


# 未証明、とりあえずソートしてどっかで区切ってみる
# test(N, LR)

LR.sort()
L, R = zip(*LR)
rsp = SparseTable(R, min)
ans = 0
for sep in range(1, N):
    max_l = L[sep - 1]
    min_r = rsp.get(0, sep)
    s1 = min_r - max_l + 1
    max_l = L[-1]
    min_r = rsp.get(sep, N)
    s2 = min_r - max_l + 1
    score = s1 + s2
    ans = max(score, ans)

# assert test(N, LR) == ans
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
u = []

for i in range(n):
    l,r = na()
    u.append((l,r,r-l+1,i))

c = sorted(u)
b = list(reversed(c))
a = sorted(u, key = lambda x: x[1])

aa = a[0][1]
bb = b[0][0]
aaa = 0
if bb < aa:
    ans = max(u, key = lambda x:x[2])[2]
    aaa = ans+(aa-bb+1)

v = a[1][1]-bb+1 if a[1][1] >= bb else 0
ans = (aa-a[0][0]+1) + v
for j in range(n-1):
    q = c[j]
    if q[3] == b[0][3] or q[3] == a[0][3]:
        continue
    e = min(c[j+1:], key = lambda x:x[1])[1]
    dif = e-bb+1 if e >= bb else 0
    ans = max(ans, (aa-q[0]+1)+dif)
v = aa-b[1][0]+1 if aa >= b[1][0] else 0
ans = max(ans, (b[0][1]-bb+1) + v)
print(max(ans,aaa))

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
u = []

for i in range(n):
    l,r = na()
    u.append((l,r,r-l+1,i))

c = sorted(u)
b = list(reversed(c))
a = sorted(u, key = lambda x: x[1])

aa = a[0][1]
bb = b[0][0]
aaa = 0
if bb < aa:
    ans = max(u, key = lambda x:x[2])[2]
    aaa = ans+(aa-bb+1)
if True:
    v = a[1][1]-bb+1 if a[1][1] >= bb else 0
    ans = (aa-a[0][0]+1) + v
    for j in range(n-1):
        q = c[j]
        if q[3] == b[0][3] or q[3] == a[0][3]:
            continue
        e = min(c[j+1:], key = lambda x:x[1])[1]
        dif = e-bb+1 if e >= bb else 0
        ans = max(ans, (aa-q[0]+1)+dif)
    v = aa-b[1][0]+1 if aa >= b[1][0] else 0
    ans = max(ans, (b[0][1]-bb+1) + v)
    print(max(ans,aaa))

Submission status: Time Limit Exceeded

Solution code:
def main():
    from sys import stdin
    input = stdin.readline
    from operator import itemgetter

    N = int(input())
    L = [0]*N
    R = [1]*N
    Lp = 0
    Rq = float("inf")
    # O(N)
    for i in range(N):
        L[i],R[i] = map(int,input().split())
        R[i] += 1
        Lp = max(Lp,L[i])
        Rq = min(Rq,R[i])

    # O(N)
    MAXRANGE = 0
    index = 0
    for l,r in zip(L,R):
        MAXRANGE = max(MAXRANGE, r-l)
        L[index] = -max(0, Rq - l)
        R[index] = max(0, r - Lp)
        index += 1

    LR = sorted([[i,j] for i,j in zip(R,L)],key=itemgetter(0,1))

    for i,[x,y] in enumerate(LR):
        L[i] = x
        R[i] = -y

    # 区間pと区間qを同じ集合に含める場合
    answer = MAXRANGE + max(0, Rq - Lp)

    # 区間pと区間qを同じ集合に含めない場合
    for i in range(1,N):
        b = min(R[:i])
        a = min(L[i:])
        answer = max(answer, a+b)

    print(answer)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from sys import stdin
    input = stdin.readline
    from operator import itemgetter

    N = int(input())
    L = [0]*N
    R = [1]*N
    Lp = 0
    Rq = float("inf")
    # O(N)
    for i in range(N):
        L[i],R[i] = map(int,input().split())
        R[i] += 1
        Lp = max(Lp,L[i])
        Rq = min(Rq,R[i])

    # O(N)
    MAXRANGE = 0
    index = 0
    for l,r in zip(L,R):
        MAXRANGE = max(MAXRANGE, r-l)
        L[index] = -max(0, Rq - l)
        R[index] = max(0, r - Lp)
        index += 1

    # O(NlogN)
    for i,[x,y] in enumerate(sorted([[i,j] for i,j in zip(R,L)],key=itemgetter(0,1))):
        L[i] = x
        R[i] = -y

    # 区間pと区間qを同じ集合に含める場合
    answer = MAXRANGE + max(0, Rq - Lp)

    # 区間pと区間qを同じ集合に含めない場合
    for i in range(1,N):
        b = min(R[:i])
        a = min(L[i:])
        answer = max(answer, a+b)

    print(answer)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from sys import stdin
    input = stdin.readline
    from operator import itemgetter

    N = int(input())
    LR = [[int(i) for i in input().split()] for _ in range(N)]
    L = [i for i,_ in LR]
    R = [i+1 for _,i in LR]

    MAXRANGE = max(r - l + 1 for l, r in LR)

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

    L = [-max(0, Rq - l) for l in L]
    R = [max(0, r - Lp) for r in R]

    LR = sorted([[i,j] for i,j in zip(R,L)],key=itemgetter(0,1))
    L = [i for i,_ in LR]
    R = [-i for _,i in LR]

    # 区間pと区間qを同じ集合に含める場合
    answer = MAXRANGE + max(0, Rq - Lp)

    # 区間pと区間qを同じ集合に含めない場合
    for i in range(1,N):
        b = min(R[:i])
        a = min(L[i:])
        answer = max(answer, a+b)

    print(answer)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline
from operator import itemgetter

N = int(input())
LR = [[int(i) for i in input().split()] for _ in range(N)]
L = [i for i,_ in LR]
R = [i+1 for _,i in LR]

MAXRANGE = max(r - l + 1 for l, r in LR)

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

L = [-max(0, Rq - l) for l in L]
R = [max(0, r - Lp) for r in R]

LR = sorted([[i,j] for i,j in zip(R,L)],key=itemgetter(0,1))
A = [i for i,_ in LR]
B = [-i for _,i in LR]

# 区間pと区間qを同じ集合に含める場合
answer = MAXRANGE + max(0, Rq - Lp)

# 区間pと区間qを同じ集合に含めない場合
for i in range(1,N):
    b = min(B[:i])
    a = min(A[i:])
    answer = max(answer, a+b)

print(answer)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline
from operator import itemgetter

N = int(input())
LR = [[int(i) for i in input().split()] for _ in range(N)]
L = [i for i,_ in LR]
R = [i+1 for _,i in LR]

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

AB = sorted([[i,j] for i,j in zip([max(0, r - Lp) for r in R],[-max(0, Rq - l) for l in L])],key=itemgetter(0,1))
A = [i for i,_ in AB]
B = [-i for _,i in AB]

# 区間pと区間qを同じ集合に含める場合
answer = max(r - l for l, r in zip(L, R)) + max(0, Rq - Lp)

# 区間pと区間qを同じ集合に含めない場合
for i in range(1,N):
    b = min(B[:i])
    a = min(A[i:])
    answer = max(answer, a+b)

print(answer)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from operator import itemgetter

N, *LR = map(int, stdin.buffer.read().split())
L = LR[::2]
R = [i+1 for i in LR[1::2]]
Lp = max(L)
Rq = min(R)

AB = sorted([[i,j] for i,j in zip([max(0, r - Lp) for r in R],[-max(0, Rq - l) for l in L])],key=itemgetter(0,1))

# 区間pと区間qを同じ集合に含める場合
answer = max(r - l for l, r in zip(L, R)) + max(0, Rq - Lp)

# 区間pと区間qを同じ集合に含めない場合
for i in range(1,N):
    b = -max(x for _,x in AB[:i])
    a = min(x for x,_ in AB[i:])
    answer = max(answer, a+b)

print(answer)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from operator import itemgetter
import numpy as np

N, *LR = map(int, stdin.buffer.read().split())
L = LR[::2]
R = [i+1 for i in LR[1::2]]
Lp = max(L)
Rq = min(R)

AB = np.array(sorted([[i,j] for i,j in zip([max(0, r - Lp) for r in R],[-max(0, Rq - l) for l in L])],key=itemgetter(0,1)))

# 区間pと区間qを同じ集合に含める場合
answer = max(r - l for l, r in zip(L, R)) + max(0, Rq - Lp)

# 区間pと区間qを同じ集合に含めない場合
for i in range(1,N):
    b = AB[:i].max(axis=0)[1]
    a = AB[i:].min(axis=0)[0]
    answer = max(answer, a-b)

print(answer)

Submission status: Time Limit Exceeded

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]
    if p == q:
        ret = max(0, 1+rq-lp) + max(0, 1+max(R)-min(L))
    else:
        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 = zip(*AB)
        for i in range(1, n):
            ret = max(ret, min(A[i:]) + min(B[:i]))

    return str(ret)


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

Submission status: Time Limit Exceeded

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
m1 = max(0, Rq - Lp + 1) + mlr
for i,a in enumerate(A2[:-1:]):
    mt = min(B2[:i+1:])
    ms = A2[i+1]
    m1 = max(m1, ms+mt)

print(m1)