ProgrammingHardTCS NQT · Accenture
Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals, sorted by end time. What is printed?
Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals, sorted by end time. What is printed?
sort intervals by end ascending
last = 0; count = 0
for each (s, e) in sorted order
if s > last then count = count + 1; last = e
end for
Print count- A. 4
- B. 1
- C. 5
- D. 2
Correct answer: A. 4
Sorted by end time the order is (2,3), (4,5), (6,7), (8,9), (1,10); the greedy takes the four short intervals and rejects (1,10), printing 4. Sorting by start picks (1,10) first and blocks everything (1), counting every interval ignores overlap (5), and requiring a gap of more than one unit between picks keeps only (2,3) and (6,7) (2).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Each event is (time, +1) for a train arriving or (time, -1) for a train departing. Arrivals are at 1, 3, 3, 5, 6, 8 and departures are at…
- Five numbers 3, 30, 34, 5, 9 are to be arranged to form the largest possible number. Two numbers x, y are put in the order that gives the…
- Prices by day: 1, 5, 3, 8, 6, 10. Profit is earned in every rise: whenever tomorrow's price is higher than today's, buy today and sell…
- Array a = [3, 1, 2, 5, 4] is sorted by bubble sort: in each pass adjacent pairs out of order are swapped (a[j] > a[j+1]). What is the…
- Items of weights 7, 3, 5, 2, 6 are considered in increasing weight order. Each item is taken if it still fits in the capacity 13. What is…
- For i from 0 to 30 inclusive, count the values of i with ii <= 30. What is printed? count = 0 for i = 0 to 30 if i i <= 30 then count =…