3085. Minimum Deletions to Make String K-Special #1834
-
Topics: You are given a string We consider Here, Return the minimum number of characters you need to delete to make Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of deletions required to make a string "k-special". A string is k-special if the absolute difference between the frequencies of any two characters in the string is at most k. The approach involves analyzing the frequencies of each character and determining the optimal target frequency range that minimizes the number of deletions. Approach
Let's implement this solution in PHP: 3085. Minimum Deletions to Make String K-Special <?php
/**
* @param String $word
* @param Integer $k
* @return Integer
*/
function minimumDeletions($word, $k) {
$freq = array();
$len = strlen($word);
for ($i = 0; $i < $len; $i++) {
$c = $word[$i];
if (!isset($freq[$c])) {
$freq[$c] = 0;
}
$freq[$c]++;
}
$freqs = array_values($freq);
$maxFreq = empty($freqs) ? 0 : max($freqs);
$candidateSet = array();
$candidateSet[0] = true;
$candidateSet[$maxFreq] = true;
foreach ($freqs as $f) {
$candidateSet[$f] = true;
$next = $f + 1;
if ($next <= $maxFreq) {
$candidateSet[$next] = true;
}
$cand1 = $f - $k;
$cand2 = $cand1 + 1;
if ($cand1 >= 0) {
$candidateSet[$cand1] = true;
}
if ($cand2 >= 0 && $cand2 <= $maxFreq) {
$candidateSet[$cand2] = true;
}
}
$candidates = array_keys($candidateSet);
$minDel = PHP_INT_MAX;
foreach ($candidates as $m) {
if ($m < 0 || $m > $maxFreq) {
continue;
}
$del = 0;
foreach ($freqs as $f) {
if ($f < $m) {
$del += $f;
} else if ($f > $m + $k) {
$del += ($f - $m - $k);
}
}
if ($del < $minDel) {
$minDel = $del;
}
}
return $minDel;
}
// Test cases
echo minimumDeletions("aabcaba", 0) . "\n"; // Output: 3
echo minimumDeletions("dabdcbdcdcd", 2) . "\n"; // Output: 2
echo minimumDeletions("aaabaaa", 2) . "\n"; // Output: 1
?> Explanation:
This approach efficiently narrows down the potential values of |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of deletions required to make a string "k-special". A string is k-special if the absolute difference between the frequencies of any two characters in the string is at most k. The approach involves analyzing the frequencies of each character and determining the optimal target frequency range that minimizes the number of deletions.
Approach
m
) in the final string. These critical points are derived from: