ProgrammingHardTCS NQT · Accenture

Events (start, end) are attended one per day, and an event may be attended on any day from start to end inclusive. Events: (1,2), (1,2), (3,3), (1,6), (3,3). The greedy below sorts events by end day and attends each on the earliest free day in its range. What is the number of events attended?

Events (start, end) are attended one per day, and an event may be attended on any day from start to end inclusive. Events: (1,2), (1,2), (3,3), (1,6), (3,3). The greedy below sorts events by end day and attends each on the earliest free day in its range. What is the number of events attended?
sort events by end ascending
taken = empty set; count = 0
for each (s, e) in sorted order
    for day = s to e
        if day not in taken then taken add day; count + 1; stop this event
    end for
end for
Print count
  1. A. 5
  2. B. 4
  3. C. 3
  4. D. 2

Correct answer: B. 4

Sorted by end: (1,2), (1,2), (3,3), (3,3), (1,6). Days 1, 2 and 3 are taken by the first three events, the second (3,3) has no free day, and (1,6) takes day 4. Counting every event gives 5, sorting by start lets the long event take day 3 and gives 3, and using only the start day gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic