<?php
$people = [
[1801, 1887],
[1943, 1943],
[1949, 2001],
[1751, 1803],
[1881, 1887],
[1956, 1983],
[1954, 1983],
[1801, 1883],
[1956, null],
[1944, 1983],
[1897, 2015],
[1965, 1997],
[1941, 1982],
[1984, null],
];
$populationPerYear = array_reduce(
$people,
static function($carry, $current) {
[$from, $to] = $current;
for($i = $from; $i <= $to; $i++) {
if (!isset($carry[$i])) {
$carry[$i] = 1;
} else {
$carry[$i]++;
}
}
return $carry;
},
[]
);
ksort($populationPerYear);
$peak = max($populationPerYear);
$peakYears = array_filter(
$populationPerYear,
static function($population) use ($peak) {
return $population === $peak;
}
);
var_dump($peak, $peakYears);
preferences:
16.15 ms | 402 KiB | 5 Q