Maximum Path Quality of a Graph LeetCode solution in JavaScript

1
var maximalPathQuality = function (values, edges, maxTime) {
2
const adjacencyList = values.map(() => []);
3
for (const [node1, node2, time] of edges) {
4
adjacencyList[node1].push([node2, time]);
5
adjacencyList[node2].push([node1, time]);
6
}
7

8
const dfs = (node, quality, time, seen) => {
9
// if we returned back to the 0 node, then we log it as a valid value
10
let best = node === 0 ? quality : 0;
11

12
// try to visit all the neighboring nodes within the maxTime
13
// given while recording the max
14
for (const [neighbor, routeTime] of adjacencyList[node]) {
15
const totalTime = time + routeTime;
16
if (totalTime > maxTime) continue;
17
if (seen.has(neighbor)) {
18
best = Math.max(best, dfs(neighbor, quality, totalTime, seen));
19
} else {
20
seen.add(neighbor);
21
best = Math.max(
22
best,
23
dfs(neighbor, quality + values[neighbor], totalTime, seen)
24
);
25
seen.delete(neighbor);
26
}
27
}
28
return best;
29
};
30
return dfs(0, values[0], 0, new Set([0]));
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0