Class Solution
-
- All Implemented Interfaces:
public final class Solution2872 - Maximum Number of K-Divisible Components\.
Hard
There is an undirected tree with
nnodes labeled from0ton - 1. You are given the integernand a 2D integer arrayedgesof lengthn - 1, where <code>edgesi = a<sub>i</sub>, b<sub>i</sub></code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.You are also given a 0-indexed integer array
valuesof lengthn, wherevalues[i]is the value associated with the <code>i<sup>th</sup></code> node, and an integerk.A valid split of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by
k, where the value of a connected component is the sum of the values of its nodes.Return the maximum number of components in any valid split.
Example 1:
Input: n = 5, edges = \[\[0,2],1,2,1,3,2,4], values = 1,8,1,4,4, k = 6
Output: 2
Explanation: We remove the edge connecting node 1 with 2. The resulting split is valid because:
The value of the component containing nodes 1 and 3 is values1 + values3 = 12.
The value of the component containing nodes 0, 2, and 4 is values0 + values2 + values4 = 6.
It can be shown that no other valid split has more than 2 connected components.
Example 2:
Input: n = 7, edges = \[\[0,1],0,2,1,3,1,4,2,5,2,6], values = 3,0,6,1,5,2,1, k = 3
Output: 3
Explanation: We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because:
The value of the component containing node 0 is values0 = 3.
The value of the component containing nodes 2, 5, and 6 is values2 + values5 + values6 = 9.
The value of the component containing nodes 1, 3, and 4 is values1 + values3 + values4 = 6.
It can be shown that no other valid split has more than 3 connected components.
Constraints:
<code>1 <= n <= 3 * 10<sup>4</sup></code>
edges.length == n - 1edges[i].length == 2<code>0 <= a<sub>i</sub>, b<sub>i</sub>< n</code>
values.length == n<code>0 <= valuesi<= 10<sup>9</sup></code>
<code>1 <= k <= 10<sup>9</sup></code>
Sum of
valuesis divisible byk.The input is generated such that
edgesrepresents a valid tree.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-