LeetCode/kt/take-k-of-each-character-from-left-and-right.kt

38 lines
811 B
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Solution {
fun takeCharacters(
s: String,
k: Int,
): Int {
val counters = IntArray(3)
// Get the frequencies
for (c in s) {
counters[c - 'a'] += 1
}
// Check for at least k characters
if (counters.any { it < k }) {
return -1
}
var l = 0
var maxWindow = 0
val window = IntArray(3)
for (r in s.indices) {
window[s[r] - 'a'] += 1
while (
l <= r &&
counters.zip(window).any { (c, w) -> c - w < k }
) {
window[s[l] - 'a'] -= 1
l += 1
}
maxWindow = listOf(maxWindow, r - l + 1).max()
}
return s.length - maxWindow
}
}