Maximum Score After Applying Operations on a Tree - DFS [JS]

Description 

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:

  1. Take the node: We get to keep all the subtree values except the current node.
  2. Skip the node: Each child subtree needs to choose one value to keep.

n = number of nodesm = 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

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]