[LeetCode] Maximum Number of K-Divisible Components

2872. Maximum Number of K-Divisible Components

There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

You are also given a 0-indexed integer array values of length n, where values[i] is the value associated with the ith node, and an integer k.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
vector<vector<int>> adj;
int dfs(int u, int par, vector<int>& A, int k, int& res) {
int sum = A[u];
for(auto& v : adj[u]) {
if(v == par) continue;
sum = (sum + dfs(v,u,A,k,res)) % k;
}
sum %= k;
if(sum == 0) res += 1;
return sum;
}
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
adj = vector<vector<int>>(n);
for(auto e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
int res = 0;
dfs(0,-1,values,k,res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/01/PS/LeetCode/maximum-number-of-k-divisible-components/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.