Skip to content

2872. Maximum Number of K-Divisible Components 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
26
27
28
29
30
31
32
class Solution {
 public:
  int maxKDivisibleComponents(int n, vector<vector<int>>& edges,
                              vector<int>& values, int k) {
    int ans = 0;
    vector<vector<int>> graph(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    dfs(graph, 0, /*prev=*/-1, values, k, ans);
    return ans;
  }

 private:
  long dfs(const vector<vector<int>>& graph, int u, int prev,
           const vector<int>& values, int k, int& ans) {
    long treeSum = values[u];

    for (const int v : graph[u])
      if (v != prev)
        treeSum += dfs(graph, v, u, values, k, ans);

    if (treeSum % k == 0)
      ++ans;
    return treeSum;
  }
};
 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
26
27
28
29
30
31
32
class Solution {
  public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
    List<Integer>[] graph = new List[n];

    for (int i = 0; i < n; i++)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    dfs(graph, 0, /*prev=*/-1, values, k);
    return ans;
  }

  private int ans = 0;

  private long dfs(List<Integer>[] graph, int u, int prev, int[] values, int k) {
    long treeSum = values[u];

    for (int v : graph[u])
      if (v != prev)
        treeSum += dfs(graph, v, u, values, k);

    if (treeSum % k == 0)
      ++ans;
    return treeSum;
  }
}
 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
26
27
28
29
class Solution:
  def maxKDivisibleComponents(
      self,
      n: int,
      edges: list[list[int]],
      values: list[int],
      k: int,
  ) -> int:
    ans = 0
    graph = [[] for _ in range(n)]

    def dfs(u: int, prev: int) -> int:
      nonlocal ans
      treeSum = values[u]

      for v in graph[u]:
        if v != prev:
          treeSum += dfs(v, u)

      if treeSum % k == 0:
        ans += 1
      return treeSum

    for u, v in edges:
      graph[u].append(v)
      graph[v].append(u)

    dfs(0, -1)
    return ans