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)- A. 14 13
- B. 13 13
- C. 14 14
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Broken-profile DP: number of ways to tile a 3 × n board with 1 × 2 dominoes, column by column with a 3-bit mask of cells already covered…
- Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is…
- All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct…
- BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)? python from collections…
- Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed? python LOG = 4…
- Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct…