Problems › TypeScript › scheduling
Most people on the floor at once
The register logs every staff entry (start) and exit (end). Find how many were present at the busiest moment.
- A person counts from start until end; at the exact end they are clocked out.
- The moments considered are the integers inside each shift.
peakStaff(slots: list<Slot>) → int
Where you start
function peakStaff(slots: Slot[]): number {
}
Worked examples
| Call | Result |
|---|---|
peakStaff([{"start":0,"end":100},{"start":50,"end":200},{"start":60,"end":80}]) | 3 |
peakStaff([{"start":0,"end":100},{"start":100,"end":200}]) | 1 |
peakStaff([]) | 0 |
peakStaff([{"start":0,"end":10},{"start":5,"end":15},{"start":10,"end":20}]) | 2 |
Hint
Build a timeline of arrivals and departures, then sweep. Or sort all events.
Reference solution in TypeScript
function peakStaff(slots: Slot[]): number {
const events: Array<[number, number]> = [];
for (const s of slots) {
events.push([s.start, 1]);
events.push([s.end, -1]);
}
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
let cur = 0;
let best = 0;
for (const [, d] of events) {
cur += d;
if (cur > best) best = cur;
}
return best;
}