Skip to content

Commit 5af9a90

Browse files
committed
add: LargestOverlapOfIntervals
1 parent 452ef7e commit 5af9a90

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
import DS.Interval;
5+
6+
/*
7+
// Definition of Interval:
8+
class Interval {
9+
public int start;
10+
public int end;
11+
public Interval(int start, int end) {
12+
this.start = start;
13+
this.end = end;
14+
}
15+
}
16+
*/
17+
18+
public class LargestOverlapOfIntervals {
19+
public int largestOverlapOfIntervals(List<Interval> intervals) {
20+
List<int[]> points = new ArrayList<>();
21+
for (Interval interval : intervals) {
22+
points.add(new int[]{interval.start, 'S'});
23+
points.add(new int[]{interval.end, 'E'});
24+
}
25+
// Sort in chronological order. If multiple points occur at the same
26+
// time, ensure end points are prioritized before start points.
27+
Collections.sort(points, (a, b) -> {
28+
if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
29+
else return Integer.compare(a[0], b[0]);
30+
});
31+
int activeInterval= 0;
32+
int maxOverlaps = 0;
33+
for (int[] point : points) {
34+
int time = point[0];
35+
int pointType = point[1];
36+
if (pointType == 'S') {
37+
activeInterval++;
38+
} else {
39+
activeInterval--;
40+
}
41+
maxOverlaps = Math.max(maxOverlaps, activeInterval);
42+
}
43+
return maxOverlaps;
44+
}
45+
}

0 commit comments

Comments
 (0)