PHP Number Of Disc Intersections
function numberOfDiscIntersections(array $a): int
{
$sum = $active = 0;
$c = count($a);
$start = $end = array_fill(0, $c, 0);
foreach ($a as $k => $v) {
$key = $k < $v ? 0 : $k - $v;
$start[$key]++;
$key = $k + $v >= $c ? $c - 1 : $k + $v;
$end[$key]++;
}
foreach ($a as $k => $v) {
$sum += $active * $start[$k] + ($start[$k] * ($start[$k] - 1)) / 2;
$active += $start[$k] - $end[$k];
if ($sum > 10000000) {
return -1;
}
}
return $sum;
}
This sorts disc start and end points and counts active overlaps without comparing every pair directly.