-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargest Color Value in a Directed Graph
More file actions
39 lines (39 loc) · 1.15 KB
/
Copy pathLargest Color Value in a Directed Graph
File metadata and controls
39 lines (39 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public int largestPathValue(String colors, int[][] edges) {
int n=colors.length();
ArrayList<ArrayList<Integer>> graph=new ArrayList<>();
for(int i=0; i<n; i++){
graph.add(new ArrayList<>());
}
int[] indegree=new int[n];
for(int[] e: edges){
int u=e[0];
int v=e[1];
graph.get(u).add(v);
indegree[v]++;
}
Queue<Integer> q=new LinkedList<>();
for(int i=0; i<n; i++){
if(indegree[i]==0){
q.add(i);
}
}
int processed=0;
int[][] cnt=new int[n][26];
int ans=0;
while(!q.isEmpty()){
int f=q.poll();
processed++;
cnt[f][colors.charAt(f)-'a']++;
ans=Math.max(ans,cnt[f][colors.charAt(f)-'a']);
for(int nbr: graph.get(f)){
indegree[nbr]--;
if(indegree[nbr]==0) q.add(nbr);
for(int c=0; c<26; c++){
cnt[nbr][c]=Math.max(cnt[nbr][c],cnt[f][c]);
}
}
}
return processed==n?ans:-1;
}
}