Data Structures & AlgorithmsHardProduct Company SDE · DAG DP

Problem: Longest path in a weighted DAG from vertex 0 with edges 0->1 (3), 1->2 (4), 0->2 (10). Run the DP over the topological order.

Problem: Longest path in a weighted DAG from vertex 0 with edges 0->1 (3), 1->2 (4), 0->2 (10). Run the DP over the topological order.
edges = {0: [(1, 3), (2, 10)], 1: [(2, 4)], 2: []}
NEG = float('-inf')
dist = {v: NEG for v in edges}
dist[0] = 0
for u in [0, 1, 2]:
    for v, w in edges[u]:
        dist[v] = max(dist[v], dist[u] + w)
print(max(dist.values()))
What is printed?
  1. A. 7
  2. B. 10
  3. C. 14
  4. D. 3

Correct answer: B. 10

The path 0->1->2 has weight 7, but the direct edge 0->2 has weight 10, which is the longest path. The DP takes the maximum over incoming edges in topological order.

More Coding Interview Problems questions

Exams that ask this topic