Largest Color Value in a Directed Graph Problem
Description
LeetCode Problem 1857.
There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.
You are given a string colors where colors[i] is a lowercase English letter representing the color of the i^th node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [a_j, b_j] indicates that there is a directed edge from node a_j to node b_j.
A valid path in the graph is a sequence of nodes x_1 -> x_2 -> x_3 -> ... -> x_k such that there is a directed edge from x_i to x_(i+1) for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.
Example 1:

Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).
Example 2:

Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.
Constraints:
n == colors.lengthm == edges.length1 <= n <= 10^50 <= m <= 10^5colorsconsists of lowercase English letters.0 <= a_j, b_j < n
Solution
Approach: Topological Sort and DP
If the graph has a cycle, the answer is -1; otherwise the best path lives in a DAG, so process nodes in topological order (Kahn's algorithm with in-degrees).
Let dp[i][c] be the largest number of nodes of color c on any path ending at node i. For an edge i -> j, update dp[j][c] = max(dp[j][c], dp[i][c] + (1 if color of j is c else 0)). Sources start with their own color counted once. The answer is the largest dp value. If fewer than n nodes were processed, there is a cycle and the answer is -1.
Complexity: O((n + m) * 26) time and O(n * 26 + m) space, for n nodes and m edges.
from collections import defaultdict, deque
class Solution:
def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
n = len(colors)
indeg = [0] * n
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
indeg[b] += 1
q = deque()
dp = [[0] * 26 for _ in range(n)]
for i, v in enumerate(indeg):
if v == 0:
q.append(i)
c = ord(colors[i]) - ord('a')
dp[i][c] += 1
cnt = 0
ans = 1
while q:
i = q.popleft()
cnt += 1
for j in g[i]:
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
c = ord(colors[j]) - ord('a')
for k in range(26):
dp[j][k] = max(dp[j][k], dp[i][k] + (c == k))
ans = max(ans, dp[j][k])
return -1 if cnt < n else ans