Explained, C++
Each component\'s sum can be only divisor of the total sum. Thus we only need to check those (~100 divisors max of a number).\n\nFor each candidate sum, we will
Each component\'s sum can be only divisor of the total sum. Thus we only need to check those (~100 divisors max of a number).\n\nFor each candidate sum, we will spend linear time to check whether it is possible to divide tree into such components with given sum, using dfs.\n\nRun dfs, and keep track of the subtree visited, when the sum of nodes in the subtree becomes equal to the potential sum, we will update our sum of subnodes to zero, and will count again until we go through entire tree. If at some point the sum is greater than potential sum, that means we cant build such a division into subtrees.\n\nAt the end, we know into how many components we were able to divide. From which we infer number of edges deleted and pick max.\n\nComplexity: n * D(sum of nodes). \nD(s) number of divisors of s.\n\n```\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < n; ++i)\n#define forbn(i, b, n) for(int i = b; i < n; ++i)\n#define sz(v) (int)v.size()\n#define pb push_back\n\ntypedef vector<int> vi;\n\n\nclass Solution {\npublic:\n\tstatic const int N = 20 * 1001;\n\tvi gr[N];\n\tvi gl_nums;\n\t\n    \n\tint dfs(int target_sm, int node, int pr = -1) {\n\t\tint loc_sm = gl_nums[node];\n\t\t\n\t\tfor(int to: gr[node]) {\n\t\t\tif(to != pr) {\n\t\t\t\tint rem = dfs(target_sm, to, node);\n\t\t\t\tloc_sm += rem;\n\t\t\t\tif(rem < 0)\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(loc_sm == target_sm) {\n\t\t\treturn 0;\n\t\t} \n\t\tif(loc_sm > target_sm) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn loc_sm;\n\t}\n\t\n    \n    int componentValue(vector<int>& nums, vector<vector<int>>& edges) {\n    \tint total = 0;\n    \tfor(int to: nums) {\n    \t\tgl_nums.pb(to);\n    \t\ttotal += to;\n    \t}\n    \t\n    \tforn(i, sz(edges)) {\n    \t\tint a = edges[i][0];\n    \t\tint b = edges[i][1];\n    \t\t\n    \t\tgr[a].pb(b);\n    \t\tgr[b].pb(a);\n    \t}\n    \t\n    \tforbn(d, 1, total + 1) {\n    \t\tif(total % d == 0) {\n    \t\t\tint ans = dfs(d, 0);\n    \t\t\tif(ans == 0) {\n    \t\t\t\tint k = total / d;\n    \t\t\t\treturn k - 1;\n    \t\t\t}\n    \t\t}\n    \t}\n        return -1;\n    }\n};\n```
[]