Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Jobs have deadlines and profits; each takes one unit of time. Schedule to maximise profit (greedy by profit, latest free slot).

Problem: Jobs have deadlines and profits; each takes one unit of time. Schedule to maximise profit (greedy by profit, latest free slot).
def schedule(jobs):
    jobs.sort(key=lambda j: -j[1])
    slots = [None] * (max(d for d, _ in jobs) + 1)
    total = 0
    for d, p in jobs:
        for t in range(d, 0, -1):
            if slots[t] is None:
                slots[t] = p; total += p; break
    return total, sum(1 for x in slots if x)
print(schedule([(2, 100), (1, 19), (2, 27), (1, 25), (3, 15)]))
What is printed?
  1. A. (127, 2)
  2. B. (152, 3)
  3. C. (142, 3)
  4. D. (167, 4)

Correct answer: C. (142, 3)

Take jobs by decreasing profit and put each in the latest free slot not after its deadline: 100 → slot 2, 27 → slot 1, 25 and 19 find no slot, 15 → slot 3. Total 142 with 3 jobs. O(n log n + n·D), or near O(n log n) with union-find on slots.

More Coding Interview Problems questions

Exams that ask this topic