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:
parent
cb85787112
commit
9b0d6ca964
1 changed files with 38 additions and 0 deletions
38
kt/take-k-of-each-character-from-left-and-right.kt
Normal file
38
kt/take-k-of-each-character-from-left-and-right.kt
Normal 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
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue