forked from theprogrammedwords/Algorithm-Solutions-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOverlappingIntervals.java
More file actions
74 lines (54 loc) · 2.12 KB
/
OverlappingIntervals.java
File metadata and controls
74 lines (54 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Problem Description
An interval is a pair of values that represents all numbers between those two.
You are given N intervals. You need to print the farthest located interval distance that are non overlapping. If there is no non-overlapping pair of intervals present, return -1
Note: Distance between two intervals is defined by the absolute difference between the end point of the left interval and start point of the right interval.
A distance of 0 means that they’re NOT overlapping. For instance, [1, 3] and [3, 4] are not considered overlapping.
Input format
There are N+1 lines of input
First line contains a single integer N. Next N lines will contain two integers, l and r, representing the start and end point of the interval respectively.
Output format
Print the farthest distance or -1 if no overlapping intervals are present.
Sample Input 1
3
1 2
3 5
6 7
Sample Output 1
4
Explanation
The pair of intervals [1,2] & [6,7] are farthest. And the distance between them will be 6 - 2 = 4
Constraints
1<=N<=10^5
1<=l<=r<=10^6
*/
import java.util.*;
class OverlappingIntervals {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> intervals = new ArrayList<ArrayList<Integer>>(n);
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
intervals.add(new ArrayList<Integer>(Arrays.asList(x, y)));
}
int result = overlappingIntervals(n, intervals);
System.out.println(result);
}
static int overlappingIntervals(int n, ArrayList<ArrayList<Integer>> intervals) {
int max_dist = -1;
int distance;
Collections.sort(intervals, (i1, i2) -> {
return i1.get(0) - i2.get(0);
});
int lastValue = intervals.get(n-1).get(0);
for(int i=0; i< n; i++){
if(lastValue > intervals.get(i).get(0)){
distance = lastValue - intervals.get(i).get(0);
max_dist = Math.max(distance, max_dist);
}
}
return max_dist;
}
}