Java Number Of Disc Intersections
public class Solution {
public static int numberOfDiscIntersections(int[] a) {
int c = a.length;
long sum = 0;
long active = 0;
int[] start = new int[c];
int[] end = new int[c];
for (int k = 0; k < c; k++) {
long v = a[k];
int key = (k < v) ? 0 : (int) (k - v);
start[key]++;
long endKey = (k + v >= c) ? c - 1 : k + v;
end[(int) endKey]++;
}
for (int k = 0; k < c; k++) {
sum += active * start[k] + (long) start[k] * (start[k] - 1) / 2;
active += start[k] - end[k];
if (sum > 10000000) {
return -1;
}
}
return (int) sum;
}
}
This sorts disc start and end points and counts active overlaps without comparing every pair directly.