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- A. 5
- B. 4
- C. 3
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Seven tasks with durations 7, 5, 4, 3, 2, 2, 1 are assigned to two identical machines. Tasks are taken in decreasing duration order, and…
- Array a = [2, 5, 3, 5]. For every pair of positions i < j, count the pairs where a[i] is at most a[j] (a[i] <= a[j]). What is the printed…
- Array a = [4, -2, 5, -1, 3]. Exactly k = 2 negations are applied: each one chooses the currently smallest element and replaces it by its…
- Tasks (duration, deadline): (3,5), (2,4), (4,9), (1,3). Earliest deadline first is applied: tasks are sorted by deadline and run back to…
- Two positive integers are a = 252 and b = 105. The procedure below finds their gcd by repeated subtraction. How many times does the loop…
- Let N = 360. The procedure below counts the divisors of N by testing every i from 1 to N. What is printed? count = 0 for i = 1 to N if N…