Maximum Score After Applying Operations on a Tree - DFS [JS]
Solution: Post-order DFS
Choose one node value to keep per leaf node path.
Use post-order DFS to find the minimum sum of node values taking one node per path (at the end, the result is total sum - dfs(0, -1))
For each dfs(node), we have two choices:
- Take the node: We get to keep all the subtree values except the current node.
- Skip the node: Each child subtree needs to choose one value to keep.
n = number of nodes, m = number of edges
Time Complexity: O(n + m)
Space Complexity: O(n + m)
var maximumScoreAfterOperations = function(edges, values) {
let n = values.length, graph = Array(n).fill(0).map(() => []);
for (let [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
let totalSum = values.reduce((sum, value) => sum + value);
return totalSum - dfs(0, -1);
function dfs(node, parent) {
if (graph[node].length === 1 && graph[node][0] === parent) {
return values[node];
}
let sum = 0;
for (let child of graph[node]) {
if (child === parent) continue;
sum += dfs(child, node);
}
return Math.min(values[node], sum);
}
};
Comments
Post a Comment