Time Efficient JS Solution - Backtracking (Beat 100% time)
\n\nPro tip: Love Justina Xi\xE8 \uD83D\uDC9C \u7231\u5C0F\u8C22 \uD83D\uDC9C\nThe hardest part of the problem is to figure out what are the constraints really 
![image.png](https://assets.leetcode.com/users/images/9b167d09-5e4c-4399-99a9-b9b4bd313ca1_1705719658.52653.png)\n\nPro tip: Love Justina Xi\xE8 \uD83D\uDC9C \u7231\u5C0F\u8C22 \uD83D\uDC9C\nThe hardest part of the problem is to figure out what are the constraints really trying to tell you. Good luck!\n\n# Complexity\n- Let `n = values.length`; `m = edges.length`; `d = max degree of a node = 4`, `l = max number of nodes (not necessarily distinct) on a valid path = maxTime / max(time[i]) <= 10`\n- Time complexity: $$O(d^l + n + m)$$\n- Space complexity: $$O(dn)$$\n\n# Code\n```js\n/**\n * @typedef {{ aNodes: number[], aTimes: number[] }} TGraphNode\n * @param {number} n\n * @param {[number,number,number?][]} edges\n * @return {TGraphNode[]}\n */\nfunction buildGraph(n, edges) {\n  /** @type {TGraphNode[]} */\n  let nodes = [];\n  for (let i = 0; i < n; i++) nodes.push({ aNodes: [], aTimes: [] });\n\n  let m = edges.length;\n  for (let i = 0; i < m; i++) {\n    let [u, v, t] = edges[i];\n    nodes[u].aNodes.push(v);\n    nodes[u].aTimes.push(t);\n    nodes[v].aNodes.push(u);\n    nodes[v].aTimes.push(t);\n  }\n\n  return nodes;\n}\n\nlet curUseds = new Uint8Array(1000);\n\n/**\n * @param {number[]} values\n * @param {number[][]} edges\n * @param {number} maxTime\n * @return {number}\n */\nvar maximalPathQuality = function (values, edges, maxTime) {\n  let n = values.length;\n  let g = buildGraph(n, edges);\n\n  let curTime = 0;\n  let curQual = 0;\n  let res = 0;\n  curUseds.fill(0, 0, n);\n\n  function bt(u) {\n    if (!curUseds[u]) curQual += values[u];\n    ++curUseds[u];\n\n    if (!u) res = Math.max(res, curQual)\n\n    let { aNodes, aTimes } = g[u];\n\n    for (let i = 0; i < aNodes.length; ++i) {\n      if (aTimes[i] + curTime <= maxTime) {\n        curTime += aTimes[i];\n        bt(aNodes[i]);\n        curTime -= aTimes[i];\n      }\n    }\n\n    --curUseds[u];\n    if (!curUseds[u]) curQual -= values[u];\n  }\n\n  bt(0);\n  return res;\n};\n```
['Backtracking', 'JavaScript']