-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Maximum Number of K-Divisible Components
- Loading branch information
1 parent
ce4376b
commit 3d94709
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
class Solution { | ||
public int maxKDivisibleComponents(int n, int[][] edges, int[] vals, int k) { | ||
if (n < 2) return 1; | ||
|
||
List<List<Integer>> graph = new ArrayList<>(); | ||
for (int i = 0; i < n; i++) graph.add(new ArrayList<>()); | ||
int[] degree = new int[n]; | ||
|
||
for (int[] edge : edges) { | ||
graph.get(edge[0]).add(edge[1]); | ||
graph.get(edge[1]).add(edge[0]); | ||
degree[edge[0]]++; | ||
degree[edge[1]]++; | ||
} | ||
|
||
long[] nodeVals = new long[n]; | ||
for (int i = 0; i < n; i++) nodeVals[i] = vals[i]; | ||
Queue<Integer> leafQ = new LinkedList<>(); | ||
for (int i = 0; i < n; i++) if (degree[i] == 1) leafQ.add(i); | ||
|
||
int compCnt = 0; | ||
while (!leafQ.isEmpty()) { | ||
int curr = leafQ.poll(); | ||
degree[curr]--; | ||
long carry = 0; | ||
|
||
if (nodeVals[curr] % k == 0) compCnt++; | ||
else carry = nodeVals[curr]; | ||
|
||
for (int nbr : graph.get(curr)) { | ||
if (degree[nbr] == 0) continue; | ||
degree[nbr]--; | ||
nodeVals[nbr] += carry; | ||
if (degree[nbr] == 1) leafQ.add(nbr); | ||
} | ||
} | ||
|
||
return compCnt; | ||
} | ||
} |