LeetCode/kt/alternating-groups-ii.kt
2025-03-09 20:40:28 +01:00

42 lines
1 KiB
Kotlin

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
}