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:
parent
a57370bdd8
commit
44a7d16cd9
1 changed files with 42 additions and 0 deletions
42
kt/alternating-groups-ii.kt
Normal file
42
kt/alternating-groups-ii.kt
Normal 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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue