29 · Topological Sort

#2050 Parallel Courses III

Hardsolve on LeetCode ↗

frequently reported atGoogleGoldman SachsAmazon

the problem

In plain words

Courses 1..n, relations[j] = [prev, next] means prev must finish before next starts, and course i takes time[i−1] months. Any number of courses can run at once. Return the minimum months to finish all courses (the graph is a DAG).

in n = 3, relations = [[1,3],[2,3]], time = [3,2,5]

out 8

1 and 2 run together; 3 starts at month 3 and ends at 8.

in n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]

out 12

Critical path 3 → 4 → 5: 3 + 4 + 5.

  • 1 ≤ n ≤ 5·10⁴
  • 0 ≤ relations.length ≤ min(n·(n−1)/2, 5·10⁴)
  • 1 ≤ time[i] ≤ 10⁴
  • The graph is a DAG

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #210
      Course Schedule II
      Mediumin Topo Sort
    2. #329
    3. #1976