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

<p>You must find the <strong>minimum</strong> number of months needed to complete all the courses following these rules:</p>

<ul>
	<li>You may start taking a course at <strong>any time</strong> if the prerequisites are met.</li>
	<li><strong>Any number of courses</strong> can be taken at the <strong>same time</strong>.</li>
</ul>

<p>Return <em>the <strong>minimum</strong> number of months needed to complete all the courses</em>.</p>

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

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://assets.leetcode.com/uploads/2021/10/07/ex1.png" style="width: 392px; height: 232px;" /></strong>

<pre>
<strong>Input:</strong> n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
<strong>Output:</strong> 8
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>
<strong><img alt="" src="https://assets.leetcode.com/uploads/2021/10/07/ex2.png" style="width: 500px; height: 365px;" /></strong>

<pre>
<strong>Input:</strong> n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
<strong>Output:</strong> 12
<strong>Explanation:</strong> 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.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= relations.length &lt;= min(n * (n - 1) / 2, 5 * 10<sup>4</sup>)</code></li>
	<li><code>relations[j].length == 2</code></li>
	<li><code>1 &lt;= prevCourse<sub>j</sub>, nextCourse<sub>j</sub> &lt;= n</code></li>
	<li><code>prevCourse<sub>j</sub> != nextCourse<sub>j</sub></code></li>
	<li>All the pairs <code>[prevCourse<sub>j</sub>, nextCourse<sub>j</sub>]</code> are <strong>unique</strong>.</li>
	<li><code>time.length == n</code></li>
	<li><code>1 &lt;= time[i] &lt;= 10<sup>4</sup></code></li>
	<li>The given graph is a directed acyclic graph.</li>
</ul>

# from collections import defaultdict
# class Solution:
#   def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
#     # sanity check
#     if not relations:
#       return max(time)
    
#     # build graph
#     adj = defaultdict(set)
#     for a, b in relations:
#       adj[b].add(a) # b depends on a
#       if a not in adj:
#         adj[a] = set()
    
#     # build time map
#     self.time = {}
#     for i in range(len(time)):
#       self.time[i+1] = time[i]

#     # topo sort
#     tasks = adj.keys()
#     visit = {}
#     self.cache = {}
#     totalTime = 0
#     for task in tasks:
#       if task not in visit:
#         cycle, time = self.dfs(task, adj, visit)
#         if cycle:
#           return -1
#         # print(time)
#         totalTime = max(time, totalTime)
#     return totalTime

#   # return [is_cycle, time]  
#   # if cycle, true. time represent total time needed 
#   def dfs(self, node, adj, visit):
#     if adj.get(node) == 1:
#       return [True, 0]
#     if adj.get(node) == 2:
#       return [False, self.cache[node]]

#     # recursive rule
#     visit[node] = 1
#     maxtime = 0
#     for nei in adj.get(node, []):
#       hasCycle, time = self.dfs(nei, adj, visit)
#       if hasCycle:
#         return [True, 0]
#       maxtime = max(maxtime, time)

#     visit[node] = 2
#     self.cache[node] = self.time[node] + maxtime
#     return [False, self.time[node] + maxtime]
class Solution:
    def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
        # Build graph (adjacency list)
        adj = defaultdict(set)
        for a, b in relations:
            adj[b].add(a)  # task `b` depends on task `a`

        # Build time map
        self.time = {i + 1: t for i, t in enumerate(time)}  # task times

        # Initialize the visit map and cache for memoization
        visit = {}
        self.cache = {}
        totalTime = 0

        # Perform DFS for each task
        for task in range(1, n + 1):  # Tasks are 1-based indexed
            if task not in visit:
                hasCycle, taskTime = self.dfs(task, adj, visit)
                if hasCycle:
                    return -1  # Return -1 if there is a cycle
                totalTime = max(totalTime, taskTime)  # Track the maximum time
        
        return totalTime

    # DFS function
    def dfs(self, node, adj, visit):
        if visit.get(node) == 1:  # Detect a cycle
            return [True, 0]
        if visit.get(node) == 2:  # Already visited
            return [False, self.cache[node]]

        # Mark the node as visiting
        visit[node] = 1
        max_time = 0

        # Traverse all the dependencies of the current node
        for nei in adj.get(node, []):
            hasCycle, time = self.dfs(nei, adj, visit)
            if hasCycle:
                return [True, 0]
            max_time = max(max_time, time)

        # Mark the node as fully visited
        visit[node] = 2
        self.cache[node] = self.time[node] + max_time
        return [False, self.cache[node]]
1376