You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.

You must find the minimum number of months needed to complete all the courses following these rules:


	You may start taking a course at any time if the prerequisites are met.
	Any number of courses can be taken at the same time.


Return the minimum number of months needed to complete all the courses.

Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).

&nbsp;
Example 1:


Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
Output: 8
Explanation: The figure above represents the given graph and the time required to complete each course. 
We start course 1 and course 2 simultaneously at month 0.
Course 1 takes 3 months and course 2 takes 2 months to complete respectively.
Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.


Example 2:


Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
Output: 12
Explanation: The figure above represents the given graph and the time required to complete each course.
You can start courses 1, 2, and 3 at month 0.
You can complete them after 1, 2, and 3 months respectively.
Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.
Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.
Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.


&nbsp;
Constraints:


	1 &lt;= n &lt;= 5 * 104
	0 &lt;= relations.length &lt;= min(n * (n - 1) / 2, 5 * 104)
	relations[j].length == 2
	1 &lt;= prevCoursej, nextCoursej &lt;= n
	prevCoursej != nextCoursej
	All the pairs [prevCoursej, nextCoursej] are unique.
	time.length == n
	1 &lt;= time[i] &lt;= 104
	The given graph is a directed acyclic graph.


class Solution:
    def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
        in_degree=defaultdict(int)
        graph=defaultdict(list)
        latest=[0]*(n+1)
        for u,v in relations:
            graph[u].append(v)
            in_degree[v]+=1
        q=[]
        for i in range(1,n+1):
            if in_degree[i]==0:
                latest[i]=time[i-1]
                q.append(i)
        while q:
            node=q.pop()
            t0=latest[node]
            for nei in graph[node]:
                t=time[nei-1]
                latest[nei]=max(latest[nei],t0+t)
                in_degree[nei]-=1
                if in_degree[nei]==0:
                    q.append(nei)
        return max(latest)
class Solution {
    public int minimumTime(int n, int[][] relations, int[] time) {
        List<Integer> adj[] = new ArrayList[n];
        int indegree[] = new int[n];
        int completionTime[] = new int[n];
        for(int i=0; i<n; i++) adj[i] = new ArrayList<>();
        for(int relation[]: relations){
            int u = relation[0]-1, v = relation[1]-1;
            adj[u].add(v);
            indegree[v]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for(int i=0; i<n; i++){
            if(indegree[i] == 0){ // if no prerequisite add it to queue
                completionTime[i] = time[i];
                q.add(i);
            }
        }

        while(!q.isEmpty()){
            int u = q.poll();
            for(int v: adj[u]){
                completionTime[v] = Math.max(completionTime[v], completionTime[u] + time[v]);
                if(--indegree[v] == 0){ // when all prerequisite are complete add the next course
                    q.add(v);
                }
            }
        }
        int res=0;
        for(int x: completionTime) res = Math.max(res, x);
        return res;
    }
}
class Solution {
public:
    int minimumTime(int n, vector<vector<int>>& relations, vector<int>& time) {
        vector<vector<int>> adjList(n);
        vector<int> inDegree(n),cTime(n,0);

        for(auto &r:relations) { // Create adjacency list and in degree count vectors.
            adjList[r[0]-1].push_back(r[1]-1);
            inDegree[r[1]-1]++;
        }
        queue<pair<int,int>> q;

        for(int i=0;i<n;i++) // Get all nodes with in-degree=0 and store add them to the queue.
            if(!inDegree[i])
                q.push({i,0});

        while(!q.empty()) {
            auto [node,t]=q.front(); // Process node `node`.
            q.pop();

            // Completion time of the current node the time when the processing started `t`
            // (Max time at which prerequisutes completed) + the time taken to process it `time[node]`.
            int completionTime=t+time[node];
            cTime[node]=completionTime; // Store the final completion time of the node `node`.

            for(int &n:adjList[node]) {
                // Update the intermediate completion time of the child node `n`.
                // This means that node `n` would start processing at least at `cTime[n]`.
                cTime[n]=max(cTime[n],completionTime);

                if(!--inDegree[n]) // Add the node with in-degree=0 to the queue.
                    q.push({n,cTime[n]});
            }
        }
        // Return the maximum time it took for a node/course to complete as our result.
        return *max_element(cTime.begin(),cTime.end());
    }
};
/**
 * @param {number} n
 * @param {number[][]} relations
 * @param {number[]} time
 * @return {number}
 */
var minimumTime = function(n, relations, time) {
    /*
    Approach: We can create reverse edges for relation.
&nbsp; &nbsp; Then longest path(by weightage of time for each node) from the node will be the minimum time to finish that course(node)
&nbsp; &nbsp; Now we can use simple DFS to find the longest path for each node.
&nbsp; &nbsp; The node containing the longest path will be course to finish the last.We can also use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again.&nbsp;
    */
    let edges={};
    for(let i=0;i<relations.length;i++){
        if(edges[relations[i][1]]===undefined){
            edges[relations[i][1]] = [];
        }
        edges[relations[i][1]].push(relations[i][0]);
    }

    let max=0,timeRequired,memo={};
    for(let i=1;i<=n;i++){
        timeRequired = longestPath(i);
        max = Math.max(max,timeRequired);
    }
    return max;
     function longestPath(node){
         if(memo[node]!==undefined){
             return memo[node];
         }
        let len,max=0;
         if(edges[node]!==undefined){
             for(let i=0;i<edges[node].length;i++){
                 len = longestPath(edges[node][i]);
                 max = Math.max(max,len);
             }
         }
         memo[node] = time[node-1]+max;//use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again
         return memo[node];
    }

};
Parallel Courses III