ProgrammingHardCapgemini · TCS NQT

Each event is (time, +1) for a train arriving or (time, -1) for a train departing. Arrivals are at 1, 3, 3, 5, 6, 8 and departures are at 4, 4, 7, 9, 10, 11 (one per train). The events are sorted by time and a running count is kept: cur = cur + 1 for an arrival, cur = cur - 1 for a departure, and best = max(best, cur) after each event. What is printed as best?

Each event is (time, +1) for a train arriving or (time, -1) for a train departing. Arrivals are at 1, 3, 3, 5, 6, 8 and departures are at 4, 4, 7, 9, 10, 11 (one per train). The events are sorted by time and a running count is kept: cur = cur + 1 for an arrival, cur = cur - 1 for a departure, and best = max(best, cur) after each event. What is printed as best?
events sorted by time, departures before arrivals at equal time
cur = 0; best = 0
for each event: update cur, then best = max(best, cur)
Print best
  1. A. 6
  2. B. 3
  3. C. 12
  4. D. 0

Correct answer: B. 3

The count peaks at 3 just before the first departure at time 4, since arrivals at 1, 3 and 3 are all present. Counting arrivals alone gives 6, treating every event as an arrival gives 12, and never updating the best gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic