Data Structures & AlgorithmsHardProduct Company SDE · greedy scheduling OA

Problem: Jobs are given as (deadline, profit): (2,100), (1,19), (2,27), (1,25), (3,15). Each job takes one unit slot and must finish by its deadline. Run the greedy code below. What is printed?

Problem: Jobs are given as (deadline, profit): (2,100), (1,19), (2,27), (1,25), (3,15). Each job takes one unit slot and must finish by its deadline. Run the greedy code below. What is printed?
jobs = [(2, 100), (1, 19), (2, 27), (1, 25), (3, 15)]
jobs.sort(key=lambda j: -j[1])
slot = [False] * 4
tot = 0
for d, p in jobs:
    for t in range(min(d, 3), 0, -1):
        if not slot[t]:
            slot[t] = True
            tot += p
            break
print(tot)
What is printed?
  1. A. 161
  2. B. 142
  3. C. 134
  4. D. 157

Correct answer: B. 142

Greedy by profit places 100 in slot 2, 27 in slot 1 (slot 2 is taken), skips 25 and 19 (no free slot by deadline 1), and places 15 in slot 3. The total is 100 + 27 + 15 = 142.

More Coding Interview Problems questions

Exams that ask this topic