kt: add «2516. Take K of Each Character From Left and Right»

URL:	https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-20 11:39:07 +01:00
parent cb85787112
commit 9b0d6ca964
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -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
}
}