int N;
struct Seg
{
int l, r, t;
bool operator <(const Seg &rhs) const{
return l < rhs.l;
}
}cow[MAXN];
int main()
{
//freopen("p4188.in", "r", stdin);
cin>>N;
for(int i = 1; i <= N; i++){
int l = read(), r = read();
cow[i] = (Seg){l, r, r - l};
}
sort(cow + 1, cow + N + 1);
int len = 0, p = 0; bool flag = false;
for(int i = 1; i <= N; i++){
if(cow[i].r <= p) flag = true;
else {
len += min(cow[i].r - cow[i].l, cow[i].r - p);
cow[i].t = min(cow[i].r - p, cow[i].r - cow[i].l);
if(i > 1 && cow[i].l < p) cow[i - 1].t -= (p - cow[i].l);
p = cow[i].r;
}
}
if(flag) cout<<len<<endl;
else{
int del = (1 << 29);
for(int i = 1; i <= N; i++) del = min(del, cow[i].t);
cout<<len - del<<endl;
}
return 0;
}