-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBiggestOverlap.java
More file actions
56 lines (45 loc) · 1.73 KB
/
BiggestOverlap.java
File metadata and controls
56 lines (45 loc) · 1.73 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
import java.util.Arrays;
public class BiggestOverlap {
static class Interval {
int start, end;
Interval(int start, int end) {
this.start = start;
this.end = end;
}
}
private static int calculateOverlap(Interval a, Interval b) {
if (a.end < b.start || b.end < a.start) {
return 0;
}
return Math.min(a.end, b.end) - Math.max(a.start, b.start) + 1;
}
private static int findMaxIntervalOverlap(Interval[] intervals, int left, int right) {
if (right - left <= 1) {
return calculateOverlap(intervals[left], intervals[right]);
}
int mid = (left + right) / 2;
int leftMax = findMaxIntervalOverlap(intervals, left, mid);
int rightMax = findMaxIntervalOverlap(intervals, mid + 1, right);
int crossMax = 0;
for (int i = left; i <= mid; i++) {
for (int j = mid + 1; j <= right; j++) {
crossMax = Math.max(crossMax, calculateOverlap(intervals[i], intervals[j]));
}
}
return Math.max(Math.max(leftMax, rightMax), crossMax);
}
public static int getMaxOverlap(Interval[] intervals) {
Arrays.sort(intervals, (a, b) -> a.start - b.start);
return findMaxIntervalOverlap(intervals, 0, intervals.length - 1);
}
public static void main(String[] args) {
Interval[] intervals = {
new Interval(1, 7),
new Interval(3, 9),
new Interval(4, 8),
new Interval(10, 12)
};
int maxOverlap = getMaxOverlap(intervals);
System.out.println("The length of the biggest overlap is: " + maxOverlap);
}
}