ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
def jobs(items):
    items = sorted(items, key=lambda x: x[0])
    h = []
    for d, p in items:
        heapq.heappush(h, p)
        if len(h) > d:
            heapq.heappop(h)
    return sum(h)
print(jobs([(2, 100), (1, 19), (2, 27), (1, 25), (3, 15)]), jobs([(1, 5), (1, 9)]))
  1. A. 127 9
  2. B. 142 9
  3. C. 142 14
  4. D. 100 9

Correct answer: B. 142 9

Process jobs by deadline and keep a min-heap of profits that the deadlines allow. Dropping the smallest profit whenever the heap overflows gives 142 for the first list and 9 for the second.

More Python Programming questions

Exams that ask this topic