From b7e7bc1b0f2a77598b44b5715180be39b98c823c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 21 Dec 2024 23:39:19 +0100 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2872.=20Maximum=20Number=20of?= =?UTF-8?q?=20K-Divisble=20Components=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/maximum-number-of-k-divisible-components/ Signed-off-by: Matej Focko --- ...aximum-number-of-k-divisible-components.go | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 go/maximum-number-of-k-divisible-components.go diff --git a/go/maximum-number-of-k-divisible-components.go b/go/maximum-number-of-k-divisible-components.go new file mode 100644 index 0000000..a2babfa --- /dev/null +++ b/go/maximum-number-of-k-divisible-components.go @@ -0,0 +1,70 @@ +package main + +import ( + aq "github.com/emirpasic/gods/v2/queues/arrayqueue" +) + +func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) int { + if n < 2 { + return 1 + } + + // create empty data structures + graph := make([][]int, n) + for i, _ := range graph { + graph[i] = make([]int, 0) + } + inDegrees := make([]int, n) + + // initialize the graph and degrees + for _, edge := range edges { + u, v := edge[0], edge[1] + + graph[u] = append(graph[u], v) + inDegrees[v]++ + + graph[v] = append(graph[v], u) + inDegrees[u]++ + } + + // Start with leafs + q := aq.New[int]() + for u, deg := range inDegrees { + if deg == 1 { + q.Enqueue(u) + } + } + + lValues := make([]int64, n) + for i, value := range values { + lValues[i] = int64(value) + } + + components := 0 + for u, ok := q.Dequeue(); ok; u, ok = q.Dequeue() { + inDegrees[u]-- + + value := int64(0) + if lValues[u]%int64(k) == 0 { + components++ + } else { + value = int64(lValues[u]) + } + + for _, v := range graph[u] { + if inDegrees[v] == 0 { + continue + } + + inDegrees[v]-- + if inDegrees[v] == 1 { + // if a new leaf + q.Enqueue(v) + } + + lValues[v] += value + } + } + + return components +}