LeetCode-in-Java

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

public class Solution {
    public int minDeletion(String s, int k) {
        int n = s.length();
        int count = 0;
        int[] carr = new int[26];
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            carr[ch - 'a']++;
        }
        int dischar = 0;
        for (int i = 0; i < 26; i++) {
            if (carr[i] > 0) {
                dischar++;
            }
        }
        while (dischar > k) {
            int minF = Integer.MAX_VALUE;
            int idx = -1;
            for (int i = 0; i < 26; i++) {
                if ((carr[i] > 0) && minF > carr[i]) {
                    minF = carr[i];
                    idx = i;
                }
            }
            count += minF;
            carr[idx] = 0;
            dischar--;
        }
        return count;
    }
}