ProgrammingHardTCS NQT · Accenture

Activities are given as (start, finish): (1,4) (3,5) (0,6) (5,7) (3,9) (5,9) (6,10) (8,11) (8,12) (2,14) (12,16). The procedure below runs on this list. What is printed?

Activities are given as (start, finish): (1,4) (3,5) (0,6) (5,7) (3,9) (5,9) (6,10) (8,11) (8,12) (2,14) (12,16). The procedure below runs on this list. What is printed?
sort activities by finish time ascending (ties keep input order)
last = -infinity; count = 0
for each (s, f) in the sorted list
    if s >= last then
        count = count + 1
        last = f
    end if
end for
Print count
  1. A. 4
  2. B. 3
  3. C. 11
  4. D. 8

Correct answer: A. 4

Sorting by finish time and always taking the earliest-ending compatible activity maximises the count. Sorting by start time gives 3, never updating last lets every activity through (11), and setting last to the start time instead of the finish time lets overlapping activities in and gives 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic