diff --git a/kt/take-k-of-each-character-from-left-and-right.kt b/kt/take-k-of-each-character-from-left-and-right.kt new file mode 100644 index 0000000..b0c5482 --- /dev/null +++ b/kt/take-k-of-each-character-from-left-and-right.kt @@ -0,0 +1,38 @@ +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 + } +}