You are given a tree having ‘N’ nodes, where each node has some coins ‘C[i]’, attached to it.
You are allowed to collect the coins from any node. Your task is to maximize the sum of chosen coins given that you cannot choose coins from adjacent nodes(i.e., nodes which are directly connected by an edge).
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains one integer ‘N’, denoting the number of nodes in the tree.
The following line contains an array ‘C’ of ‘N’ spaced integers denoting the number of coins attached to each node.
The following line ‘N’ - 1 contains two integers ‘x’ and ‘y’ denoting that there is an edge between node ‘x’ and node ‘y’.
Output Format:
For each test case, print a single integer denoting the maximum coins you can collect.
Note:
You don't have to take input or output you just have to complete the function.
1 <= T <= 5
1 <= N <= 10^5
1 <= C[i] <= 10^9
1 <= x, y <= N
Time Limit: 1 sec
2
4
1 2 5 4
1 2
2 3
2 4
3
6 5 4
1 2
1 3
10
9
In the first test case, you can take 1st, 3rd and 4th node which will give you a total of 10 coins.
In the second test case, you can take the 2nd and 3rd nodes which will give you a total of 9 coins.
2
3
9 1 3
1 2
1 3
3
2 2 2
1 2
2 3
9
4
Can we check all possible ways to take the coins and find the maximum possible way?
Now let’s take a simple tree.
Now if we take coins at node 1 then for sure we can not take coins present at nodes 2 and 3, but if we skip node 1 then, we have two options for each of the other two nodes .i.e we can either take or skip them.
To generalise this, we can say that if we take the parent node, we need to skip all its direct children nodes and if we skip the parent node, we can either take its children node or skip it.
Let F(x, b) be a recursive function that takes a node and a boolean value and depending upon the boolean value it returns the maximum number of coins we can take from the subtree of that node.
F(x, 1) = ‘C[x]’ + F(y1, 0) + F(y2, 0) + F(y3, 0) + … F(yn, 0).
F(x, 0) = max(F(y1, 0), F(y1, 1) + max(F(y2, 0), F(y2,1) + .. max(F(yn,0), F(yn,1).
Since we need to find the maximum number of coins we can take from the whole tree so the final answer is going to be the maximum of F(root,0) and F(root,1).
Algorithm:
O(2^N), where ‘N’ is the number of nodes in the tree.
For each node, we have two options, either to take it or skip it and we are finding all possible combinations, so total time complexity becomes O(2^N).
O(N), where ‘N’ is the number of nodes in the tree.
Storing the nodes in adjacency vector and recursively calling children nodes will lead to a space complexity of O(N)