|
| 1 | +/** |
| 2 | + * @param {string} colors |
| 3 | + * @param {number[][]} edges |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +const largestPathValue = function(colors, edges) { |
| 7 | + const n = colors.length; |
| 8 | + const m = edges.length; |
| 9 | + const adj = Array(n).fill(0).map(() => []); |
| 10 | + const inDegree = Array(n).fill(0); |
| 11 | + for (const [u, v] of edges) { |
| 12 | + adj[u].push(v); |
| 13 | + inDegree[v]++; |
| 14 | + } |
| 15 | + let res = 1 |
| 16 | + const colorSet = new Set(colors); |
| 17 | + const a = 'a'.charCodeAt(0); |
| 18 | + for(const e of colorSet) { |
| 19 | + const tmp = helper(e.charCodeAt(0) - a); |
| 20 | + if(tmp === -1) return -1; |
| 21 | + res = Math.max(res, tmp); |
| 22 | + } |
| 23 | + |
| 24 | + return res |
| 25 | + |
| 26 | + function code(ch) { |
| 27 | + return ch.charCodeAt(0) - 'a'.charCodeAt(0); |
| 28 | + } |
| 29 | + function helper(k) { |
| 30 | + const ind = [...inDegree]; |
| 31 | + const count = Array(n).fill(0); |
| 32 | + let nodes = 0 |
| 33 | + let res = 0 |
| 34 | + let q = [] |
| 35 | + for(let i = 0; i < n; i++) { |
| 36 | + if(ind[i] === 0) { |
| 37 | + q.push(i); |
| 38 | + nodes++ |
| 39 | + count[i] = code(colors[i]) === k ? 1 : 0; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + while(q.length) { |
| 44 | + const size = q.length; |
| 45 | + const tmp = [] |
| 46 | + for(let i = 0; i < size; i++) { |
| 47 | + const e = q[i]; |
| 48 | + for(const v of adj[e]) { |
| 49 | + count[v] = Math.max(count[v], count[e] + (code(colors[v]) === k ? 1 : 0)); |
| 50 | + res = Math.max(res, count[v]); |
| 51 | + ind[v]--; |
| 52 | + if(ind[v] === 0) { |
| 53 | + tmp.push(v); |
| 54 | + nodes++ |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + q = tmp |
| 60 | + } |
| 61 | + |
| 62 | + return nodes === n ? res : -1 |
| 63 | + } |
| 64 | +}; |
| 65 | + |
| 66 | +// another |
| 67 | + |
1 | 68 | /**
|
2 | 69 | * @param {string} colors
|
3 | 70 | * @param {number[][]} edges
|
|
0 commit comments