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])- A. 5 (12, 16)
- B. 4 (8, 11)
- C. 4 (12, 16)
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Huffman coding: frequencies a:5, b:9, c:12, d:13, e:16, f:45. What is the total number of bits to encode the text? python import heapq f =…
- Longest common subsequence: what is the length and one LCS read back from the table (preferring the upper cell on ties)? python a, b =…
- Edit distance between "kitten" and "sitting", and between "intention" and "execution". What is printed? python def ed(a, b): prev =…
- Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?…
- What is printed? (level-order traversal of the BST built from these keys) python def insert(t, k): if t is None: return [k, None, None] i…
- What is printed? (inorder successor in a BST) python def insert(t, k): if t is None: return [k, None, None] i = 1 if k < t[0] else 2 t[i]…