Drill

ProblemsTypeScript › scheduling

Most people on the floor at once

mediumschedulingTypeScript

The register logs every staff entry (start) and exit (end). Find how many were present at the busiest moment.

peakStaff(slots: list<Slot>) → int

Solve it in the editor →

Where you start

function peakStaff(slots: Slot[]): number {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More scheduling problems in TypeScript