2872. Maximum Number of K-Divisible Components #981
-
Topics: There is an undirected tree with You are also given a 0-indexed integer array 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 Return the maximum number of components in any valid split. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can implement a Depth-First Search (DFS) approach to explore the tree, track the values of components, and find the maximum number of valid splits. Key Points:
Approach:
Plan:
Solution Steps:
Let's implement this solution in PHP: 2872. Maximum Number of K-Divisible Components <?php
/**
* @param Integer $n
* @param Integer[][] $edges
* @param Integer[] $values
* @param Integer $k
* @return Integer
*/
function maxKDivisibleComponents($n, $edges, $values, $k) {
$ans = 0;
$graph = array_fill(0, $n, []);
// Build the adjacency list for the graph
foreach ($edges as $edge) {
$u = $edge[0];
$v = $edge[1];
$graph[$u][] = $v;
$graph[$v][] = $u;
}
// Start DFS traversal
dfs($graph, 0, -1, $values, $k, $ans);
return $ans;
}
/**
* DFS Function
*
* @param $graph
* @param $node
* @param $parent
* @param $values
* @param $k
* @param $ans
* @return array|bool|int|int[]|mixed|null
*/
private function dfs($graph, $node, $parent, &$values, $k, &$ans) {
$treeSum = $values[$node];
foreach ($graph[$node] as $neighbor) {
if ($neighbor !== $parent) {
$treeSum += $this->dfs($graph, $neighbor, $node, $values, $k, $ans);
}
}
// If the subtree sum is divisible by k, it forms a valid component
if ($treeSum % $k === 0) {
$ans++;
return 0; // Reset sum for the current component
}
return $treeSum;
}
// Example 1
$n = 5;
$edges = [[0,2],[1,2],[1,3],[2,4]];
$values = [1,8,1,4,4];
$k = 6;
echo maxKDivisibleComponents($n, $edges, $values, $k) . "\n"; // Output: 2
// Example 2
$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;
echo maxKDivisibleComponents($n, $edges, $values, $k) . "\n"; // Output: 3
?> Explanation:
Example Walkthrough:Example 1: Input:
DFS starts from node 0:
Example 2: Input:
DFS starts from node 0:
Time Complexity:
Thus, the overall time and space complexity is O(n), making this approach efficient for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
We can implement a Depth-First Search (DFS) approach to explore the tree, track the values of components, and find the maximum number of valid splits.
Key Points:
k
.k
, it means the subtree can be considered as a valid component by itself.