cswork / OAOpen practice workspace

AmazonOA #316

Optimal Interval Difference

Estimated MediumJudge-ready

Topics (AI-labelled)Prefix & RangesIn-place Arrays

First merge all intersecting closed intervals into disjoint maximal segments; sharing an endpoint also counts as intersecting. Find the minimum gap between any two adjacent merged segments, that is, the start of the later segment minus the end of the earlier one. If fewer than two segments remain after merging, there is no gap to compare, and the output is −1 as this site's protocol specifies.

Input

The first line contains n, followed by n lines of start end. On this site 1≤n≤200000, −10^9≤start≤end≤10^9. The −1 encoding is only added for the case with no gap; single-segment inputs are not excluded.

Output

Output a single integer, the answer.

Example 1

Input:

3
1 4
2 5
8 11

Output:

3

Example 2

Input:

2
1 5
5 7

Output:

-1

Example 3

Input:

3
1 1
3 3
8 8

Output:

2

Example notes

The answers are 3, −1 and 2. The original description swaps the indices in start[i−1] and end[i]; following the original example 7−5=2, this site consistently uses the later segment's start minus the earlier segment's end.

Editorial

Loading solution…