Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8f1561c

Browse files
Create OverlappingIntervals.java
1 parent f2bcd32 commit 8f1561c

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

‎Arrays/OverlappingIntervals.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
Problem Description
3+
An interval is a pair of values that represents all numbers between those two.
4+
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
5+
6+
7+
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.
8+
A distance of 0 means that they’re NOT overlapping. For instance, [1, 3] and [3, 4] are not considered overlapping.
9+
10+
Input format
11+
There are N+1 lines of input
12+
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.
13+
14+
Output format
15+
Print the farthest distance or -1 if no overlapping intervals are present.
16+
17+
Sample Input 1
18+
3
19+
1 2
20+
3 5
21+
6 7
22+
23+
Sample Output 1
24+
4
25+
26+
Explanation
27+
The pair of intervals [1,2] & [6,7] are farthest. And the distance between them will be 6 - 2 = 4
28+
29+
Constraints
30+
1<=N<=10^5
31+
32+
1<=l<=r<=10^6
33+
*/
34+
35+
import java.util.*;
36+
37+
class OverlappingIntervals {
38+
public static void main(String args[]) {
39+
Scanner sc = new Scanner(System.in);
40+
41+
int n = sc.nextInt();
42+
43+
ArrayList<ArrayList<Integer>> intervals = new ArrayList<ArrayList<Integer>>(n);
44+
45+
for (int i = 0; i < n; i++) {
46+
int x = sc.nextInt();
47+
int y = sc.nextInt();
48+
intervals.add(new ArrayList<Integer>(Arrays.asList(x, y)));
49+
}
50+
51+
int result = overlappingIntervals(n, intervals);
52+
53+
System.out.println(result);
54+
}
55+
56+
static int overlappingIntervals(int n, ArrayList<ArrayList<Integer>> intervals) {
57+
58+
int max_dist = -1;
59+
int distance;
60+
61+
Collections.sort(intervals, (i1, i2) -> {
62+
return i1.get(0) - i2.get(0);
63+
});
64+
65+
int lastValue = intervals.get(n-1).get(0);
66+
for(int i=0; i< n; i++){
67+
if(lastValue > intervals.get(i).get(0)){
68+
distance = lastValue - intervals.get(i).get(0);
69+
max_dist = Math.max(distance, max_dist);
70+
}
71+
}
72+
return max_dist;
73+
}
74+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /