From 9b0d6ca9643c08a80f11c14924b55ee7b193cf9b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 20 Nov 2024 11:39:07 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2516.=20Take=20K=20of=20Each?= =?UTF-8?q?=20Character=20From=20Left=20and=20Right=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/ Signed-off-by: Matej Focko --- ...k-of-each-character-from-left-and-right.kt | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 kt/take-k-of-each-character-from-left-and-right.kt 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 + } +}