Parallel Courses III

HardGraphstopological sort

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n courses labeled 1 to n. relations[i] = [a, b] means course a must be **completed** before course b can start. time[i] is how many months course i + 1 takes. You may take any number of courses at the same time, and a course can start the moment all of its prerequisites are finished. The prerequisite graph is guaranteed to be acyclic, so every course can be completed. Return the minimum number of months needed to finish all n courses.

Examples

Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
Output: 8
Courses 1 and 2 start at month 0 and finish at 3 and 2; course 3 starts at month 3 and finishes at 8.
Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
Output: 12
Course 4 finishes at 3 + 4 = 7, so course 5 starts at 7 and finishes at 12.

Constraints

  • 1 <= n <= 5 * 10^4
  • 0 <= relations.length <= min(n * (n - 1) / 2, 5 * 10^4)
  • relations[i] = [a, b] with 1 <= a, b <= n and a != b
  • all pairs are unique and the graph is a DAG
  • time.length == n
  • 1 <= time[i] <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More topological sort problems