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?- A. (127, 2)
- B. (152, 3)
- C. (142, 3)
- 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
- Problem: Given n ≤ 10⁵ intervals, find the minimum number of points such that every interval contains at least one point. Which greedy…
- Problem: Given n balloons as horizontal intervals, find the minimum number of vertical arrows that burst all of them (a balloon bursts if…
- Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary. python def insert(iv, new): out, i…
- Problem: n ≤ 10⁵ trains arrive and depart at given minutes. Find the minimum number of platforms. Which approach is O(n log n) and correct?
- Problem: Assign cookies of sizes s to children with greed factors g (a child is content if cookie ≥ greed). Maximise content children…
- Problem: A staircase has n steps; you climb 1 or 2 steps at a time. Count the distinct ways to reach the top. cpp long long ways(int n) {…