Javascript - Topological Sort + BFS
Code\n\n/**\n * @param {number[]} nums\n * @param {number[][]} edges\n * @return {number}\n */\nvar componentValue = function (nums, edges) {\n  const n = nums.
# Code\n```\n/**\n * @param {number[]} nums\n * @param {number[][]} edges\n * @return {number}\n */\nvar componentValue = function (nums, edges) {\n  const n = nums.length;\n  const degrees = new Array(n).fill(0);\n  const graph = new Array(n).fill().map((_) => []);\n\n  for (const [v1, v2] of edges) {\n    graph[v1].push(v2);\n    graph[v2].push(v1);\n    degrees[v1]++;\n    degrees[v2]++;\n  }\n\n  let sum = 0;\n  const queue = [];\n  for (let i = 0; i < n; i++) {\n    if (degrees[i] === 1) queue.push(i);\n    sum += nums[i];\n  }\n\n  for (let i = n; i >= 1; i--) {\n    if (sum % i !== 0) continue;\n    const result = bfs(\n      sum / i,\n      degrees.slice(),\n      queue.slice(),\n      nums.slice(),\n      graph\n    );\n    if (result) return i - 1;\n  }\n\n  return 0;\n};\n\nfunction bfs(target, degrees, queue, nums, graph) {\n  while (queue.length) {\n    const curr = queue.shift();\n    degrees[curr] = 0;\n    for (const next of graph[curr]) {\n      if (nums[curr] !== target) nums[next] += nums[curr];\n      degrees[next]--;\n      if (degrees[next] === 0) return nums[next] === target;\n      if (degrees[next] === 1) queue.push(next);\n    }\n  }\n\n  return false; // unreachable\n}\n\n```
['Breadth-First Search', 'Topological Sort', 'JavaScript']