|
3 | 3 | * @param {number[][]} edges
|
4 | 4 | * @return {number}
|
5 | 5 | */
|
6 |
| - const largestPathValue = function(colors, edges) { |
7 |
| - const graph = {} |
8 |
| - const n = colors.length, a = 'a'.charCodeAt(0) |
9 |
| - const indegree = Array(colors.length).fill(0) |
10 |
| - for(let e of edges) { |
11 |
| - if(graph[e[0]] == null) graph[e[0]] = [] |
12 |
| - graph[e[0]].push(e[1]) |
13 |
| - indegree[e[1]]++ |
| 6 | +const largestPathValue = function (colors, edges) { |
| 7 | + const graph = {} |
| 8 | + const n = colors.length, |
| 9 | + a = 'a'.charCodeAt(0) |
| 10 | + const indegree = Array(colors.length).fill(0) |
| 11 | + for (let e of edges) { |
| 12 | + if (graph[e[0]] == null) graph[e[0]] = [] |
| 13 | + graph[e[0]].push(e[1]) |
| 14 | + indegree[e[1]]++ |
| 15 | + } |
| 16 | + const cnt = Array.from({ length: n }, () => Array(26).fill(0)) |
| 17 | + const q = [] |
| 18 | + for (let i = 0; i < n; i++) { |
| 19 | + if (indegree[i] === 0) { |
| 20 | + q.push(i) |
| 21 | + cnt[i][colors.charCodeAt(i) - a] = 1 |
14 | 22 | }
|
15 |
| - const cnt = Array.from({ length: n }, () => Array(26).fill(0)) |
16 |
| - const q = [] |
17 |
| - for(let i = 0; i < n; i++) { |
18 |
| - if(indegree[i] === 0) { |
19 |
| - q.push(i) |
20 |
| - cnt[i][colors.charCodeAt(i) - a] = 1 |
| 23 | + } |
| 24 | + let res = 0, |
| 25 | + seen = 0 |
| 26 | + while (q.length) { |
| 27 | + const u = q[0] |
| 28 | + q.shift() |
| 29 | + let val = Math.max(...cnt[u]) |
| 30 | + res = Math.max(res, val) |
| 31 | + seen++ |
| 32 | + if (graph[u] == null) continue |
| 33 | + for (let v of graph[u]) { |
| 34 | + for (let i = 0; i < 26; i++) { |
| 35 | + cnt[v][i] = Math.max( |
| 36 | + cnt[v][i], |
| 37 | + cnt[u][i] + (i === colors.charCodeAt(v) - a) |
| 38 | + ) |
21 | 39 | }
|
| 40 | + if (--indegree[v] === 0) q.push(v) |
22 | 41 | }
|
23 |
| - let res = 0, seen = 0 |
24 |
| - while(q.length) { |
25 |
| - const u = q[0] |
26 |
| - q.shift() |
27 |
| - let val = Math.max(...cnt[u]) |
28 |
| - res = Math.max(res, val) |
29 |
| - seen++ |
30 |
| - if(graph[u] == null) continue |
31 |
| - for(let v of graph[u]) { |
32 |
| - for(let i = 0; i < 26; i++) { |
33 |
| - cnt[v][i] = Math.max(cnt[v][i], cnt[u][i] + (i === colors.charCodeAt(v) - a)) |
34 |
| - } |
35 |
| - if(--indegree[v] === 0) q.push(v) |
36 |
| - } |
37 |
| - } |
38 |
| - return seen < colors.length ? -1 : res |
39 |
| - }; |
40 |
| - |
41 |
| - |
| 42 | + } |
| 43 | + return seen < colors.length ? -1 : res |
| 44 | +} |
0 commit comments