Under construction

Still being built. Things may change

Overflowing Fandom

Interview

Time limit1sMemory limit256 MB

Summary
Given N intervals during which fans are at school, find the minimum length of a single visit window that meets every interval.
Level

Medium4 of 10

Topics
Intervals, Greedy, Sorting, Array
Solved
No attempts yet

Problem

Wookje, having ruined a gift-wrapping factory, now sells boiled chicken in a valley and cannot often go to school. But the life of a world-class star is tiring! Even in hard times like these, Wookje must occasionally visit school for the 5 trillion 500 million devoted fans waiting for him. He has to watch the boiling chicken, so he cannot leave the shop for long. So Wookje plans to go to school once, stay for the minimum amount of time, greet every fan once, and leave.

Wookje can arrive at or leave school at any moment, and makes only one round trip. He can finish greeting several fans at the same time. Wookje is so handsome that a greeting makes fans collapse on the spot, so the time needed to greet is 0.

For example, suppose the times three fans A, B, C stay at school are as in <Figure 1>. Here all three fans are at school at time 2, so Wookje can arrive at time 2, greet all three at once, and return straight to the shop. Times 3 and 4 work the same way. In this case the total time Wookje stays at school is 0.

As another example, suppose the times two fans A and B are at school are as in <Figure 2>. Wookje can stay at school from time 4 to time 5, greet A at time 4 and B at time 5, then leave. Here Wookje's time at school is 1.

Hyobin, the kitchen aunt at the boiled chicken shop, secretly investigated the times [s, e] that N fans stay at school. She plans to compute the time Wookje stays at school and slack off during it. Let us compute, together with Hyobin, the minimum time Wookje must stay at school!

Input

The first line gives N, the number of Wookje's devoted fans. (1 ≤ N ≤ 100,000)

Each of the next N lines gives integers si, ei in order (1 ≤ si ≤ ei ≤ 100,000). This means the time [si, ei] that the i-th fan is at school.

Output

Output the minimum time Wookje must stay at school.

Examples2

  1. Example 1

    Input
    3
    2 5
    1 4
    2 4
    
    Expected output
    0
    
  2. Example 2

    Input
    2
    1 4
    5 6
    
    Expected output
    1