Skip to content

Commit 84111a8

Browse files
committed
Time: 99 ms (93.48%), Space: 35.6 MB (83.33%) - LeetHub
1 parent 531861a commit 84111a8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# time complexity: O(n+m)
2+
# space complexity: O(n+m)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int:
8+
adjList = [[] for _ in range(n)]
9+
for node1, node2 in edges:
10+
adjList[node1].append(node2)
11+
adjList[node2].append(node1)
12+
13+
componentCount = [0]
14+
self.dfs(0, -1, adjList, values, k, componentCount)
15+
16+
return componentCount[0]
17+
18+
def dfs(self, currNode: int, parentNode: int, adjList: List[List[int]],
19+
nodeValues: List[int], k: int, componentCount: List[int]) -> int:
20+
21+
total = 0
22+
for neighborNode in adjList[currNode]:
23+
if neighborNode != parentNode:
24+
total += self.dfs(neighborNode, currNode,
25+
adjList, nodeValues, k, componentCount)
26+
total %= k
27+
total += nodeValues[currNode]
28+
total %= k
29+
if total == 0:
30+
componentCount[0] += 1
31+
32+
return total
33+
34+
35+
n = 5
36+
edges = [[0, 2], [1, 2], [1, 3], [2, 4]]
37+
values = [1, 8, 1, 4, 4]
38+
k = 6
39+
print(Solution().maxKDivisibleComponents(n, edges, values, k))

0 commit comments

Comments
 (0)