kt: add «3208. Alternating Groups II»

URL:	https://leetcode.com/problems/alternating-groups-ii/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-09 20:40:28 +01:00
parent a57370bdd8
commit 44a7d16cd9
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,42 @@
class Solution {
private data class Acc(val last: Int, val count: Int, val groups: Int) {
constructor(last: Int) : this(last, 1, 0)
fun update(
k: Int,
color: Int,
): Acc {
val count =
when {
color == last -> {
1
}
else -> {
count + 1
}
}
val groups =
when {
count >= k -> groups + 1
else -> groups
}
return copy(
last = color,
count = count,
groups = groups,
)
}
}
fun numberOfAlternatingGroups(
colors: IntArray,
k: Int,
): Int =
(1..colors.size + k - 2)
.map { i -> i % colors.size }
.fold(Acc(colors[0])) { acc, i ->
acc.update(k, colors[i])
}.groups
}