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: Time Limit Exceeded

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

        # 別日に実施する場合
        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_ = min(LRs[j][R] for j in range(x[IND] + 1, N) if j != min_r[IND])
            # ここでTLEになるはず
            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: Time Limit Exceeded

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

_n = int(input())
lrlist, Lp, Rq = [], 0, 10 ** 9
for _ in range(_n):
    l, r = map(int, input().split())
    lrlist.append((l, r))
    Lp, Rq = max(Lp, l), min(Rq, r)

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

ans = max([r - l + 1 for l, r in lrlist]) + max(Rq - Lp + 1, 0)
for i in range(1, _n):
    s, t = st[:i], st[i:]
    min_b, min_a = sorted(s, key=itemgetter(1))[0][1], t[0][0]

    ans = max(min_a + min_b, ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int(input())
l = []
r = []
for i in range(n):
    li, ri = map(int, input().split())
    l.append(li)
    r.append(ri+1)

arglmax = l.index(max(l))
argrmin = r.index(min(r))
num = 0
for i in range(n):
    num = max(r[i] - l[i], num)
ans1 = num + max(0, r[argrmin]-l[arglmax])

lst = [l, r]
lst = list(np.array(lst).T)
lst = sorted(lst, key=lambda x: (x[0]), reverse=True)
lst = sorted(lst, key=lambda x: (x[1]))
lst = list(np.array(lst).T)
sorted_l = list(lst[0])
sorted_r = list(lst[1])

sorted_r_minus_lmax = list(np.array(sorted_r)-l[arglmax])
mini = sorted_r_minus_lmax[n-1]
for i in range(1, n):
    mini = min(mini, sorted_r_minus_lmax[n-1-i])
    sorted_r_minus_lmax[n-1-i] = mini

ans2 = 0
for i in range(n-1):
    ai = max(0, sorted_r_minus_lmax[i+1])
    bi = max(0, min(r[argrmin]-np.array(sorted_l[:i+1])))
    ans2 = max(ans2, ai+bi)

print(max(ans1, ans2))

Submission status: Time Limit Exceeded

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

def fan(lr):
    lmax = lr[-1][0]
    rl = [lr[i][1] for i in range(len(lr))]
    rmax = min(rl)
    return max(rmax-lmax+1,0)
res = 0
for i in range(1,n):
    lr1 = lr[:i]
    lr2 = lr[i:]
    res = max(res,fan(lr1)+fan(lr2))
print(res)

Submission status: Time Limit Exceeded

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

import sys
from operator import itemgetter, add

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

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

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

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

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

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

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

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

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

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

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

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

zipped, unzipped = compress(A)

LR.sort(key=itemgetter(0))

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

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

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

def check3(m):
    return st3.query(m, len(zipped)) == 0

def check4(m):
    return st4.query(0, m+1) == 0

ans = 0
# 1区間だけ独立させるケース
for i in range(N):
    l1, r1 = LR[i]
    st1.update(zipped[l1], st1.get(zipped[l1])-1)
    st2.update(zipped[r1], st2.get(zipped[r1])-1)

    idx = bisearch_min(-1, len(zipped), check1) - 1
    l2 = unzipped[idx]
    idx = bisearch_max(0, len(zipped)+1, check2) + 1
    r2 = unzipped[idx]
    ans = max(ans, max(r1-l1+1, 0) + max(r2-l2+1, 0))

    st1.update(zipped[l1], st1.get(zipped[l1])+1)
    st2.update(zipped[r1], st2.get(zipped[r1])+1)

# ある場所から半分に分けるケース
st3 = SegTree(len(zipped), add, 0)
st4 = SegTree(len(zipped), add, 0)
for i in range(N-1):
    l, r = LR[i]
    st1.update(zipped[l], st1.get(zipped[l])-1)
    st2.update(zipped[r], st2.get(zipped[r])-1)
    st3.update(zipped[l], st3.get(zipped[l])+1)
    st4.update(zipped[r], st4.get(zipped[r])+1)

    idx = bisearch_min(-1, len(zipped), check1) - 1
    l1 = unzipped[idx]
    idx = bisearch_max(0, len(zipped)+1, check2) + 1
    r1 = unzipped[idx]
    idx = bisearch_min(-1, len(zipped), check3) - 1
    l2 = unzipped[idx]
    idx = bisearch_max(0, len(zipped)+1, check4) + 1
    r2 = unzipped[idx]
    ans = max(ans, max(r1-l1+1, 0) + max(r2-l2+1, 0))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int(input())
l = []
r = []
ind = []
for i in range(n):
    li, ri = map(int, input().split())
    l.append(li)
    r.append(ri+1)
    ind.append(i)

arglmax = l.index(max(l))
argrmin = r.index(min(r))
num = 0
for i in range(n):
    num = max(r[i] - l[i], num)
ans1 = num + max(0, r[argrmin]-l[arglmax])

lst = [l, r, ind]
lst = list(np.array(lst).T)
lst = sorted(lst, key=lambda x: (x[0]), reverse=True)
lst = sorted(lst, key=lambda x: (x[1]))
lst = list(np.array(lst).T)
sorted_l = list(lst[0])
sorted_r = list(lst[1])
sorted_ind = list(lst[2])

ans2 = 0
for i in range(n-1):
    ai = max(0, min(np.array(sorted_r[i+1:])-l[arglmax]))
    bi = max(0, min(r[argrmin]-np.array(sorted_l[:i+1])))
    ans2 = max(ans2, ai+bi)

print(max(ans1, ans2))

Submission status: Time Limit Exceeded

Solution code:
import sys
from io import StringIO
import unittest
from operator import itemgetter


class Problem():
    def __init__(self, l, r):
        self.l = l
        self.r = r

    def __str__(self):
        return "l:{}, r:{}, diff:{}".format(
            self.l, self.r, self.r-self.l
        )


def calc_joy(problems):
    r = min(problems, key=lambda p: p.r).r
    l = max(problems, key=lambda p: p.l).l
    return max(r-l + 1, 0)


def resolve():
    N = int(input())

    problems = []
    for i in range(N):
        l, r = map(int, input().split())
        problems.append(Problem(l, r))

    problems = sorted(problems, reverse=True, key=lambda p: p.l)
    problems = sorted(problems, key=lambda p: p.r)

    # for p in problems:
    # print(p)

    joy_max = 0
    others = []
    for i in range(len(problems) - 1):
        others.append(problems.pop())
        joy1 = calc_joy(problems)
        joy2 = calc_joy(others)
        joy_max = max(joy_max, joy1+joy2)
        # print('-------')
        # print(len(problems))
        # print(len(others))
        # print(joy1)
        # print(joy2)
        # print('-------')

    print(joy_max)


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """4
4 7
1 4
5 8
2 5"""
        output = """6"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """4
1 20
2 19
3 18
4 17"""
        output = """34"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526"""
        output = """540049931"""
        self.assertIO(input, output)


if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
N, = map(int, input().split())
mx, md, my = 0, 0, 10**9
ps = []

class SegTree:
    def __init__(self, init_val, n, ide_ele, seg_func):
        self.segfunc = seg_func
        self.num = 2**(n-1).bit_length()
        self.ide_ele = ide_ele
        self.seg=[self.ide_ele]*2*self.num
        for i in range(n):
            self.seg[i+self.num-1]=init_val[i]    
        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


for _ in range(N):
    x, y = map(int, input().split())
    mx = max(x, mx)
    my = min(y, my)
    md = max(y-x+1, md)
    ps.append((x,y))

ps.sort()
if ps[-1][1] == my:
    print(my-mx+1+md)
    sys.exit()

from collections import deque
rs = []
dq = deque()
for i in range(1, N):
    while True:
        if not len(dq):
            dq.append(i)
            break
        lxi = dq[-1]
        if ps[i][1] > ps[lxi][1]:
            dq.append(i)
            break
        dq.pop()

r = 0
#SegTree(pys, N-1, 10**9, min)
y = ps[dq.popleft()][1]
for i in range(N-1):
    x = ps[i][0]
    if len(dq):
        if i+1 == dq[0]:
            #print(dq)
            y = ps[dq.popleft()][1] # mx
    #print(y,min(p[1] for p in ps[i+1:]))
    y = min(p[1] for p in ps[i+1:])
    r = max(r, max(my - x + 1, 0) + max(y - mx + 1, 0))
print(r)

Submission status: Time Limit Exceeded

Solution code:
def get_common_rng(lr):
  rng = [-float('inf'),float('inf')]
  for l, r in lr:
    rng[0] =max(rng[0], l)
    rng[1] =min(rng[1], r)
  return rng

def tasu_common_rng(rng1, rng2):
  return [max(rng1[0], rng2[0]), min(rng1[1], rng2[1])]

N = int(input())
LR = sorted([list(map(int,input().split())) for _ in range(N)])
rng1 = LR[0]
rng2 = get_common_rng(LR[1:])
ans = (rng1[1]-rng1[0]+1)+(rng2[1]-rng2[0]+1)

for i in range(1,N-1):
  rng1 = tasu_common_rng(rng1, LR[i])
  rng2 = get_common_rng(LR[i+1:])
  ans = max(ans, (rng1[1]-rng1[0]+1)+(rng2[1]-rng2[0]+1))
  prv_rng1 = rng1
  prv_rng2 = rng2
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def pleasure(a,b):
    if a[1]<b[0] or b[1]<a[0]:
        return [0,-1]
    if a[0]<=b[0]<=a[1]<=b[1]:
        return [b[0],a[1]]
    if a[0]<=b[0]<=b[1]<=a[1]:
        return [b[0],b[1]]
    if b[0]<=a[0]<=b[1]<=a[1]:
        return [a[0],b[1]]
    if b[0]<=a[0]<=a[1]<=b[1]:
        return [a[0],a[1]]

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

max_l = 0
max_l_problem = 0
min_r = 10**9+1
min_r_problem = 0
for i in range(N):
    now_l = List[i][0]
    max_l = max(max_l, now_l)
    now_r = List[i][1]
    min_r = min(min_r, now_r)

# Rが大きいものから順にfirst_contestに入れ、残りはsecond_contest
# その中で楽しさ最大のものを選ぶ
ans1 = 0
List_sorted = sorted(List, key=lambda x: (-x[1], x[0]))
for i in range(1,len(List_sorted)):
    List_first_contest = List_sorted[0:i]
    List_second_contest = List_sorted[i:N]
    first_pleasure = max(List_first_contest[-1][1] - max_l + 1, 0)
    second_pleasure = max(min_r - List_second_contest[0][0] + 1, 0)
    #print(List_first_contest, List_second_contest, first_pleasure, second_pleasure)
    if ans1 < first_pleasure+second_pleasure:
        ans1 = first_pleasure+second_pleasure

# 最長問題1つだけのコンテストをつくるパターン
max_len = 0
max_len_problem = 0
for i in range(N):
    now_len = List[i][1]-List[i][0]+1
    if max_len < now_len:
        max_len = now_len
        max_len_problem = i
first_contest = List[max_len_problem]

# 最長問題以外を片方のコンテストに入れる
second_contest = [1,10**9]
for i in range(N):
    if i == max_len_problem:
        continue
    second_contest = pleasure(second_contest,List[i])
        
ans2 = first_contest[1]-first_contest[0]+1+second_contest[1]-second_contest[0]+1

print(max(ans1,ans2))

Submission status: Time Limit Exceeded

Solution code:
def pleasure(a,b):
    if a[1]<b[0] or b[1]<a[0]:
        return [0,-1]
    if a[0]<=b[0]<=a[1]<=b[1]:
        return [b[0],a[1]]
    if a[0]<=b[0]<=b[1]<=a[1]:
        return [b[0],b[1]]
    if b[0]<=a[0]<=b[1]<=a[1]:
        return [a[0],b[1]]
    if b[0]<=a[0]<=a[1]<=b[1]:
        return [a[0],a[1]]

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

# Lが最大の問題をfirst_contestにする
max_l = 0
max_l_problem = 0
for i in range(N):
    now_l = List[i][0]
    if max_l < now_l:
        max_l = now_l
        max_l_problem = i
first_contest = List[max_l_problem]

# Rが最小の問題をsecond_contestにする
min_r = 10**9+1
min_r_problem = 0
for i in range(N):
    now_r = List[i][1]
    if min_r > now_r:
        min_r = now_r
        min_r_problem = i
second_contest = List[min_r_problem]

# Rが大きいものから順にfirst_contestに入れ、残りはsecond_contest
# その中で楽しさ最大のものを選ぶ
ans1 = 0
List_sorted = sorted(List, key=lambda x:-x[1]) #R降順
for i in range(1,len(List_sorted)):
    List_first_contest = List_sorted[0:i]
    List_second_contest = List_sorted[i:N]
    first_pleasure = max(List_first_contest[-1][1] - List[max_l_problem][0] + 1, 0)
    second_pleasure = max(List[min_r_problem][1] - List_second_contest[0][0] + 1, 0)
    ans1 = max(ans1, first_pleasure+second_pleasure)


# 最長問題1つだけのコンテストをつくるパターン
max_len = 0
max_len_problem = 0
for i in range(N):
    now_len = List[i][1]-List[i][0]+1
    if max_len < now_len:
        max_len = now_len
        max_len_problem = i
first_contest = List[max_len_problem]

# 最長問題以外を片方のコンテストに入れる
second_contest = [1,10**9]
for i in range(N):
    if i == max_len_problem:
        continue
    second_contest = pleasure(second_contest,List[i])
        
ans2 = first_contest[1]-first_contest[0]+1+second_contest[1]-second_contest[0]+1

print(max(ans1,ans2))

Submission status: Time Limit Exceeded

Solution code:
def pleasure(a,b):
    if a[1]<b[0] or b[1]<a[0]:
        return [0,-1]
    if a[0]<=b[0]<=a[1]<=b[1]:
        return [b[0],a[1]]
    if a[0]<=b[0]<=b[1]<=a[1]:
        return [b[0],b[1]]
    if b[0]<=a[0]<=b[1]<=a[1]:
        return [a[0],b[1]]
    if b[0]<=a[0]<=a[1]<=b[1]:
        return [a[0],a[1]]

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

# Lが最大の問題をfirst_contestにする
max_l = 0
max_l_problem = 0
for i in range(N):
    now_l = List[i][0]
    if max_l < now_l:
        max_l = now_l
        max_l_problem = i
first_contest = List[max_l_problem]

# Rが最小の問題をsecond_contestにする
min_r = 10**9+1
min_r_problem = 0
for i in range(N):
    now_r = List[i][1]
    if min_r > now_r:
        min_r = now_r
        min_r_problem = i
second_contest = List[min_r_problem]

# Rが大きいものから順にfirst_contestに入れ、残りはsecond_contest
# その中で楽しさ最大のものを選ぶ
ans1 = 0
List_sorted = sorted(List, key=lambda x:-x[1]) #R降順
for i in range(1,len(List_sorted)):
    List_first_contest = List_sorted[0:i]
    List_second_contest = sorted(List_sorted[i:N], key=lambda x:-x[0]) #L降順
    first_pleasure = max(List_first_contest[-1][1] - List[max_l_problem][0] + 1, 0)
    second_pleasure = max(List[min_r_problem][1] - List_second_contest[0][0] + 1, 0)
    #print(List_first_contest, List_second_contest, first_pleasure, second_pleasure)
    ans1 = max(ans1, first_pleasure+second_pleasure)


# 最長問題1つだけのコンテストをつくるパターン
max_len = 0
max_len_problem = 0
for i in range(N):
    now_len = List[i][1]-List[i][0]+1
    if max_len < now_len:
        max_len = now_len
        max_len_problem = i
first_contest = List[max_len_problem]

# 最長問題以外を片方のコンテストに入れる
second_contest = [1,10**9]
for i in range(N):
    if i == max_len_problem:
        continue
    second_contest = pleasure(second_contest,List[i])
        
ans2 = first_contest[1]-first_contest[0]+1+second_contest[1]-second_contest[0]+1

print(max(ans1,ans2))

Submission status: Time Limit Exceeded

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

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

    answer = 0
    for i in range(1,N):
        a = 0
        mi = 0
        ma = 10**9
        for lr in LR[:i]:
            mi = max(lr[0],mi)
            ma = min(lr[1],ma)
        a += ma-mi+1
        
        mi = 0
        ma = 10**9
        for lr in LR[i:]:
            mi = max(lr[0],mi)
            ma = min(lr[1],ma)
        a += ma-mi+1

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



    return


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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N = int(input())

L_R = [list(map(int, input().split())) for i in range(N)]
L_R_sort = sorted(L_R, key=lambda k: k[0])
np_L_R_sort = np.array(L_R_sort)
# print(np_L_R_sort[:2])
# print(np_L_R_sort[:2].min(axis=0)[1])
max_point = 0
for i in range(1, N):
    point = 0

    L_max = np_L_R_sort[:i].max(axis=0)[0]
    R_min = np_L_R_sort[:i].min(axis=0)[1]
    point += max(R_min - L_max + 1, 0)
    L_max = np_L_R_sort[i:].max(axis=0)[0]
    R_min = np_L_R_sort[i:].min(axis=0)[1]
    point += max(R_min - L_max + 1, 0)
    if max_point > point:
        continue
    else:
        max_point = point
print(max_point)

Submission status: Time Limit Exceeded

Solution code:
n= int(input())
G = [list(map(int,input().split())) for i in range(n)]

ans = 0
for i in range (2**n):
    # first_l = []
    # first_r = []
    # second_l = []
    # second_r = []
    first_l_max = 0
    first_r_min = 10000000000000
    second_l_max = 0
    second_r_min = 10000000000000
    for j in range(n):
        if (i>>j) & 1:
            if G[j][0] > first_l_max:
                first_l_max = G[j][0]
            if G[j][1] < first_r_min:
                first_r_min = G[j][1]
        else:
            if G[j][0] > second_l_max:
                second_l_max = G[j][0]
            if G[j][1] < second_r_min:
                second_r_min = G[j][1]
    if (first_r_min != 10000000000000) and (second_r_min != 10000000000000):
        first_diff = first_r_min - first_l_max+1
        second_diff = second_r_min - second_l_max+1
        tmp = first_diff + second_diff
        ans = max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def get_common_rng(lr):
  rng = [-float('inf'),float('inf')]
  for l, r in lr:
    rng[0] =max(rng[0], l)
    rng[1] =min(rng[1], r)
  return rng[1]-rng[0]+1

N = int(input())
LR = sorted([list(map(int,input().split())) for _ in range(N)])
ans = -float('inf')
for i in range(1,N):
  ans = max(ans, get_common_rng(LR[:i])+get_common_rng(LR[i:]))
  #print(i,ans, LR[:i], LR[i:])
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n= int(input())
G = [list(map(int,input().split())) for i in range(n)]

ans = 0
for i in range (2**n):
    # first_l = []
    # first_r = []
    # second_l = []
    # second_r = []
    first_l_max = 0
    first_r_min = 10000000000000
    second_l_max = 0
    second_r_min = 10000000000000
    for j in range(n):
        if (i>>j) & 1:
            first_l_max = max(first_l_max,G[j][0])
            first_r_min = min(first_r_min,G[j][1])
        else:
            second_l_max = max(second_l_max,G[j][0])
            second_r_min = min(second_r_min,G[j][1])
    if (first_r_min != 10000000000000) and (second_r_min != 10000000000000):
        first_diff = first_r_min - first_l_max+1
        second_diff = second_r_min - second_l_max+1
        tmp = first_diff + second_diff
        ans = max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())
seikai = []
for _ in range(n):
  L, R = map(int, input().split(' '))
  seikai.append([L, R])
  
# print(n)
# print(seikai)


def calc_fun(index_list):
  seikai_L = 0
  seikai_R = 10**9
  for i in index_list:
    L, R = seikai[i]
    # print('L: {}, R: {}'.format(L, R))
    if seikai_L < L:
      seikai_L = L
    if seikai_R > R:
      seikai_R = R
    
    if seikai_L > seikai_R:
      return 0
  return seikai_R - seikai_L + 1

ans = 0
all_index = [i for i in range(n)]
for first in range(1, round(n / 2)+1):
  # print('first_round_count: {}=============='.format(first))
  for index_list in itertools.combinations(all_index, first):
    first_fun = calc_fun(index_list)
    # print('first index: {}'.format(index_list))
    # print('first round fun: {}'.format(first_fun))
    
    second_index = list(set(all_index) - set(index_list))
    second_fun = calc_fun(second_index)
    # print('second round fun: {}'.format(second_fun))
    
    if ans < (first_fun + second_fun):
      ans = first_fun + second_fun

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

L_R = []
for i in range(N):
    L_R.append(list(map(int, input().split())))
L_R_sort = sorted(L_R, key=lambda k: k[0])

max_point = 0
L_max = 1
R_min = 10**9
for i in range(1, N):
    point = 0
    # print(L_R_sort[:i], "      " ,L_R_sort[i:])
    for l_r in L_R_sort[:i]:
        if L_max < l_r[0]:
            L_max = l_r[0]
        if R_min > l_r[1]:
            R_min = l_r[1]
    point += max(R_min - L_max + 1, 0)
    # print(L_max, R_min, point)
    L_max = 1
    R_min = 10**9
    for l_r in L_R_sort[i:]:
        if L_max < l_r[0]:
            L_max = l_r[0]
        if R_min > l_r[1]:
            R_min = l_r[1]
    point += max(R_min - L_max + 1, 0)
    # print(L_max, R_min, point)
    L_max = 1
    R_min = 10**9
    # print(i, point, max_point)
    if max_point > point:
        continue
    else:
        max_point = point
print(max_point)

Submission status: Time Limit Exceeded

Solution code:
n= int(input())
G = [list(map(int,input().split())) for i in range(n)]

ans = 0
for i in range (2**n):
    first_l = []
    first_r = []
    second_l = []
    second_r = []
    for j in range(n):
        if (i>>j) & 1:
            first_l.append(G[j][0])
            first_r.append(G[j][1])
        else:
            second_l.append(G[j][0])
            second_r.append(G[j][1])
    if (first_l != []) and (second_l != []):
        first_diff = min(first_r) - max(first_l)+1
        second_diff = min(second_r) - max(second_l)+1
        tmp = first_diff + second_diff
        ans = max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
ls=[]
for i in range(N):
  ls.append(list(map(int,input().split())))
L1=1
R1=1000000000
L2=1
R2=1000000000
co=[]
for bit in range(1<<N):
  for i in range(N):
    if bit&(1<<i):
      L1=max([L1,ls[i][0]])
      R1=min([R1,ls[i][1]])
    else:
      L2=max([L2,ls[i][0]])
      R2=min([R2,ls[i][1]])
  co.append(max([0,R1-L1+1])+max([0,R2-L2+1]))
  #print([L1,R1,L2,R2])
  L1=1
  R1=1000000000
  L2=1
  R2=1000000000
  
#print(co[1:2**N-1])
#print(co)
print(max(co[1:2**N-1]))

Submission status: Time Limit Exceeded

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)
#
#         if left_a == right_a:
#             return max(0, right_b - left_b + 1)
#
#         if left_b == right_b:
#             return max(0, right_a - left_a + 1)
#
#     return max(0, right_a - left_a + 1) + max(0, right_b - left_b + 1)
#
#
# def f():
#     N = int(input())
#     W = list(set([tuple(map(int, input().split())) for _ in range(N)]))
#
#     res = 0
#     left_a = 0
#     right_a = 10 ** 9
#     for k, w in enumerate(W):
#         left_b, right_b = w
#         if left_a == right_a:
#             res = max(res, right_b - left_b + 1)
#             continue
#
#         if k:
#             res = max(res, calc(left_a, right_a, left_b, right_b, W[k + 1:]))
#
#         left_a = max(left_b, left_a)
#         right_a = min(right_b, right_a)
#         if left_a > right_a:
#             left_a = right_a
#
#     print(res)

def calc(L):
    if len(L) == 0:
       return -10 ** 18

    left = 0
    right = 10 ** 9
    for l in L:
        left = max(left, l[0])
        right = min(right, l[1])

    return max(0, right - left + 1)


def f():
    N = int(input())
    W = sorted(list(([tuple(map(int, input().split())) for _ in range(N)])))
    sorted(W, key=lambda x: x[1], reverse=True)

    res = 0
    for k in range(N):
        res = max(res, calc(W[:k]) + calc(W[k:]))
    print(res)


if __name__ == '__main__':
    f()