LeetCode in Kotlin

3545. Minimum Deletions for At Most K Distinct Characters

Easy

You are given a string s consisting of lowercase English letters, and an integer k.

Your task is to delete some (possibly none) of the characters in the string so that the number of distinct characters in the resulting string is at most k.

Return the minimum number of deletions required to achieve this.

Example 1:

Input: s = “abc”, k = 2

Output: 1

Explanation:

Example 2:

Input: s = “aabb”, k = 2

Output: 0

Explanation:

Example 3:

Input: s = “yyyzz”, k = 1

Output: 2

Explanation:

Constraints:

Solution

class Solution {
    fun minDeletion(s: String, k: Int): Int {
        val n = s.length
        var count = 0
        val carr = IntArray(26)
        for (i in 0..<n) {
            val ch = s[i]
            carr[ch.code - 'a'.code]++
        }
        var dischar = 0
        for (i in 0..25) {
            if (carr[i] > 0) {
                dischar++
            }
        }
        while (dischar > k) {
            var minF = Int.Companion.MAX_VALUE
            var idx = -1
            for (i in 0..25) {
                if ((carr[i] > 0) && minF > carr[i]) {
                    minF = carr[i]
                    idx = i
                }
            }
            count += minF
            carr[idx] = 0
            dischar--
        }
        return count
    }
}