Skip to content

Commit 8e6531f

Browse files
authored
Merge branch 'main' into temp
2 parents 7e165b3 + 1906101 commit 8e6531f

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Use Topological Sorting (Kahn’s Algorithm) + Dynamic Programming.
2+
3+
// For each node, maintain a count[node][color] array of size 26.
4+
5+
// When processing a node, propagate color counts to its neighbors.
6+
7+
// Keep track of max color count during traversal.
8+
9+
// If all nodes are processed → return max count; else → cycle → -1.
10+
11+
12+
#include <iostream>
13+
#include <vector>
14+
#include <queue>
15+
#include <unordered_map>
16+
#include <string>
17+
#include <algorithm>
18+
#include <climits>
19+
using namespace std;
20+
21+
class Solution {
22+
public:
23+
int largestPathValue(string colors, vector<vector<int>>& edges) {
24+
int n=colors.size();
25+
vector<vector<int>> graph(n);
26+
vector<int> indegree(n, 0);
27+
28+
29+
for (auto &e:edges) {
30+
graph[e[0]].push_back(e[1]);
31+
indegree[e[1]]++;
32+
}
33+
34+
35+
queue<int> q;
36+
for (int i=0;i<n;i++)
37+
if (indegree[i]==0)
38+
q.push(i);
39+
40+
vector<vector<int>> count(n,vector<int>(26, 0));
41+
int vis=0;
42+
int ans=0;
43+
44+
while (!q.empty()) {
45+
int u=q.front();
46+
q.pop();
47+
vis++;
48+
49+
50+
int colorIdx=colors[u]-'a';
51+
count[u][colorIdx]++;
52+
ans=max(ans,count[u][colorIdx]);
53+
54+
for(int v:graph[u]) {
55+
for(int c=0;c<26;c++)
56+
count[v][c] = max(count[v][c],count[u][c]);
57+
if(--indegree[v]==0)
58+
q.push(v);
59+
}
60+
}
61+
62+
return (vis==n)?ans:-1;
63+
}
64+
};

0 commit comments

Comments
 (0)