Maximum Subgraph Score in a Tree

You are given an undirected tree consisting of n nodes, numbered from 0 to n - 1. The tree is represented by a 2D array edges of length n - 1, where edges[i] = [a, b] indicates an edge between node a and node b.

You are also given an array good of length n, where good[i] is 1 if the node is "good" and 0 if it is "bad".

The score of a connected subgraph is calculated as the total number of good nodes minus the total number of bad nodes in it.

For each node i, you must find the maximum possible score among all valid connected subgraphs that contain node i. Return an array of n integers where the i-th element is this maximum score for node i.

Example 1:

Input: n = 3, edges = [[0,1], [1,2]], good = [0, 0, 0]

Output: [-1, -1, -1]

Explanation:

All nodes have a value of -1. Expanding any subgraph only adds more negative values. Therefore, the maximum score for every node is achieved by taking just the node itself, resulting in a score of -1.

Example 2:

Input: n = 4, edges = [[0,1], [0,2], [1,3]], good = [0, 1, 1, 0]
Output: [1, 1, 1, 0]

Explanation:

Converting good to values: [-1, 1, 1, -1].

Node 0 (-1): The best connected subgraph is {0, 1, 2}. Score: -1 + 1 + 1 = 1.

Node 1 (1): Taking just {1} gives 1. Taking {1, 0, 2} also gives 1. Best score is 1.

Node 2 (1): Taking just {2} gives 1. Best score is 1.

Node 3 (-1): Taking just {3} gives -1. Adding {1} gives 0. Adding {1, 0, 2} gives 0. Best score is 0.

Now Your Turn!

Pick the correct output for the given input

Input: n = 3, edges = [[0,1],[1,2]], good = [1,1,1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n <= 105
  • edges.length == n - 1
  • edges[i] = [a, b]
  • 0 <= a, b < n
  • good.length == n
  • 0 <= good[i] <= 1
  • The input guarantees that edges represents a valid tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> maxScore(int n, vector<vector<int>>& edges, vector<int>& good) {
}
};
Test Case

Input:

Edges
Good
N