File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n + m)
2
+ // Space: O(n + m)
3
+
4
+ class Solution {
5
+ public:
6
+ int largestPathValue (string colors, vector<vector<int >>& edges) {
7
+ vector<vector<int >> adj (size (colors));
8
+ vector<int > in_degree (size (colors));
9
+ for (const auto & edge : edges) {
10
+ adj[edge[0 ]].emplace_back (edge[1 ]);
11
+ ++in_degree[edge[1 ]];
12
+ }
13
+ vector<int > q;
14
+ for (int i = 0 ; i < size (colors); ++i) {
15
+ if (!in_degree[i]) {
16
+ q.emplace_back (i);
17
+ }
18
+ }
19
+ vector<vector<int >> dp (size (colors), vector<int >(26 ));
20
+ int result = -1 , cnt = 0 ;
21
+ while (!empty (q)) {
22
+ vector<int > new_q;
23
+ for (const auto & u : q) {
24
+ ++cnt;
25
+ result = max (result, ++dp[u][colors[u] - ' a' ]);
26
+ for (const auto & v : adj[u]) {
27
+ for (int c = 0 ; c < 26 ; ++c) {
28
+ dp[v][c] = max (dp[v][c], dp[u][c]);
29
+ }
30
+ if (!--in_degree[v]) {
31
+ new_q.emplace_back (v);
32
+ }
33
+ }
34
+ }
35
+ q = move (new_q);
36
+ }
37
+ return cnt == size (colors) ? result : -1 ;
38
+ }
39
+ };
You can’t perform that action at this time.
0 commit comments