1647. Equal Share Cuts

A pipeline network has n junctions numbered 0..n-1 connected by n - 1 pipes in edges (a tree). Junction i stores values[i] units of water, always a positive number.

You may close any set of pipes. Closing pipes breaks the network into separate groups, and the water of a group is the sum of the values of its junctions. Find the largest number of pipes that can be closed so that all resulting groups hold exactly the same amount of water, and return that number (0 if no pipe can be closed).

Hint of the intended approach: if there are c groups then c divides the total, and each group holds total/c. Try the divisors from large to small with one bottom-up pass each. The order of pairs in edges is arbitrary. Target O(n) work per candidate, avoid deep recursion.

Example 1

Input:
n = 6edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]values = [3,1,2,2,1,3]
Output:
3
Explanation:

The path splits into [3],[1,2],[2,1],[3], four groups of sum 3, by deleting 3 edges; no finer equal split exists.

Example 2

Input:
n = 5edges = [[0,1],[0,2],[0,3],[0,4]]values = [5,1,1,1,1]
Output:
0
Explanation:

The total is 9 and the node of value 5 cannot sit in a part of sum 3 or less, so nothing can be cut.

Example 3

Input:
n = 7edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]values = [1,1,1,1,1,1,1]
Output:
6
Explanation:

Seven equal values give total 7, and seven singleton parts are possible by deleting all 6 edges.

Constraints

1 ≤ n ≤ 2*104
1 ≤ values[i] ≤ 50
edges has n - 1 pairs [u, v] describing a tree on nodes 0..n-1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n * d(S))
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…