Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

Activity selection: activities (start, finish). How many can one person attend, and which?

Activity selection: activities (start, finish). How many can one person attend, and which?
acts = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11), (8, 12), (2, 14), (12, 16)]
acts.sort(key=lambda a: a[1]); end = -1; chosen = []
for s, f in acts:
    if s >= end: chosen.append((s, f)); end = f
print(len(chosen), chosen[-1])
  1. A. 5 (12, 16)
  2. B. 4 (8, 11)
  3. C. 4 (12, 16)
  4. D. 3 (12, 16)

Correct answer: C. 4 (12, 16)

Sort by finish time and take each activity starting at or after the last finish: (1,4), (5,7), (8,11), (12,16) → 4. Earliest finish leaves the most room for the rest (exchange argument). O(n log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic