Data Structures & AlgorithmsVery hardProduct company OA

Weighted interval scheduling (start, end, value): DP over jobs sorted by end time with binary search for the last compatible job, versus the earliest-finish greedy that ignores values. What is printed?

Weighted interval scheduling (start, end, value): DP over jobs sorted by end time with binary search for the last compatible job, versus the earliest-finish greedy that ignores values. What is printed?
import bisect
jobs = [(1, 4, 5), (3, 5, 1), (0, 6, 10), (4, 7, 4), (3, 9, 6), (5, 9, 3), (6, 10, 2), (8, 11, 4)]
jobs.sort(key=lambda j: j[1])
ends = [j[1] for j in jobs]
dp = [0] * (len(jobs) + 1)
for i, (s, e, v) in enumerate(jobs, 1):
    k = bisect.bisect_right(ends, s, 0, i - 1)
    dp[i] = max(dp[i - 1], dp[k] + v)
greedy, last = 0, -1
for s, e, v in jobs:
    if s >= last: greedy += v; last = e
print(dp[-1], greedy)
  1. A. 14 13
  2. B. 13 13
  3. C. 14 14
  4. D. 17 13

Correct answer: A. 14 13

dp[i] = max(dp[i − 1], value_i + dp[p(i)]), where p(i) counts jobs ending no later than job i's start (bisect_right on the end times). The best plan is (0, 6, 10) + (8, 11, 4) = 14. Earliest-finish greedy is optimal only when every job is worth the same: here it picks (1, 4, 5), (4, 7, 4), (8, 11, 4) = 13. 17 adds overlapping jobs. O(n log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic