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

Solution in Rust (1.15.1) (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    }};

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

const INF: i64 = 1 << 50;

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }
    input! {
        n: usize,
        lr: [(i64, i64); n],
    }
    let lr: Vec<_> = lr.into_iter().map(|(l, r)| (l, r + 1))
        .collect();
    let mut ev = vec![];
    for i in 0..n {
        let (l, r) = lr[i];
        ev.push((l, n + i));
        ev.push((r, i));
    }
    ev.sort();
    // Do we have two segments s1, s2 s.t. s1 /\ s2 = {}?
    let mut idx = 2 * n;
    for i in 0..2 * n - 1 {
        if ev[i].1 < n && ev[i + 1].1 >= n {
            idx = i;
            break;
        }
    }
    let mut ma = 0;
    for &(l, r) in &lr {
        ma = max(ma, r - l);
    }
    if idx >= 2 * n {
        let mut ls = vec![];
        let mut rs = vec![];
        for &(l, r) in &lr {
            ls.push(l);
            rs.push(r);
        }
        ls.sort(); ls.reverse();
        rs.sort();
        for i in 0..n {
            let (l, r) = lr[i];
            let ol = if ls[0] == l {
                ls[1]
            } else {
                ls[0]
            };
            let or = if rs[0] == r {
                rs[1]
            } else {
                rs[0]
            };
            ma = max(ma, r - l + max(0, or - ol));
        }
        let mut mal = (-INF, 0);
        let mut mir = (INF, 0);
        for i in 0..n {
            let (l, r) = lr[i];
            mal = max(mal, (l, i));
            mir = min(mir, (r, i));
        }
        if mal.1 != mir.1 {
            let (l1, r1) = lr[mal.1];
            let (l2, r2) = lr[mir.1];
            let mut rem = vec![];
            for i in 0..n {
                if i != mal.1 && i != mir.1 {
                    rem.push(lr[i]);
                }
            }
            rem.sort();
            let m = rem.len();
            let mut acc = vec![INF; m + 1];
            for i in (0..m).rev() {
                acc[i] = min(acc[i + 1], rem[i].1);
            }
            ma = max(ma, max(0, min(r1, acc[0]) - l1) + max(0, r2 - l2));
            for i in 1..m + 1 {
                ma = max(ma, max(0, min(r1, acc[i]) - l1)
                         + max(0, r2 - max(l2, rem[i - 1].0)));
            }
        }
    } else {
        let i1 = ev[idx].1;
        let i2 = ev[idx + 1].1 - n;
        let (mut l1, mut r1) = lr[i1];
        let (mut l2, mut r2) = lr[i2];
        let mut pool = vec![];
        for &(l, r) in &lr {
            if r <= l2 {
                l1 = max(l1, l);
                r1 = min(r1, r);
            } else if l >= r1 {
                l2 = max(l2, l);
                r2 = min(r2, r);
            } else {
                pool.push((l, r));
            }
        }
        pool.sort();
        let m = pool.len();
        let mut acc = vec![INF; m + 1];
        for i in (0..m).rev() {
            let (_, r) = pool[i];
            acc[i] = min(acc[i + 1], r);
        }
        ma = max(ma, max(0, r1 - l1) + max(0, min(acc[0], r2) - l2));
        for i in 1..m + 1 {
            ma = max(ma, max(0, r1 - max(l1, pool[i - 1].0)) +
                     max(0, min(acc[i], r2) - l2));
        }
    }
    puts!("{}\n", ma);
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}