-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (75 loc) · 2.43 KB
/
main.go
File metadata and controls
84 lines (75 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Source: https://leetcode.com/problems/minimum-deletions-to-make-string-k-special
// Title: Minimum Deletions to Make String K-Special
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// You are given a string `word` and an integer `k`.
//
// We consider `word` to be **k-special** if `|freq(word[i]) - freq(word[j])| <= k` for all indices `i` and `j` in the string.
//
// Here, `freq(x)` denotes the frequency of the character `x` in `word`, and `|y|` denotes the absolute value of `y`.
//
// Return the **minimum** number of characters you need to delete to make `word` **k-special**.
//
// **Example 1:**
//
// ```
// Input: word = "aabcaba", k = 0
// Output: 3
// Explanation: We can make `word` `0`-special by deleting `2` occurrences of `"a"` and `1` occurrence of `"c"`. Therefore, `word` becomes equal to `"baba"` where `freq('a') == freq('b') == 2`.
// ```
//
// **Example 2:**
//
// ```
// Input: word = "dabdcbdcdcd", k = 2
// Output: 2
// Explanation: We can make `word` `2`-special by deleting `1` occurrence of `"a"` and `1` occurrence of `"d"`. Therefore, `word` becomes equal to "bdcbdcdcd" where `freq('b') == 2`, `freq('c') == 3`, and `freq('d') == 4`.
// ```
//
// **Example 3:**
//
// ```
// Input: word = "aaabaaa", k = 2
// Output: 1
// Explanation: We can make `word` `2`-special by deleting `1` occurrence of `"b"`. Therefore, `word` becomes equal to `"aaaaaa"` where each letter's frequency is now uniformly `6`.
// ```
//
// **Constraints:**
//
// - `1 <= word.length <= 10^5`
// - `0 <= k <= 10^5`
// - `word` consists only of lowercase English letters.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package main
import (
"slices"
)
// We have two approach
// 1. keep the rarest character, and delete the more common characters.
// 2. Delete the rarest character, and try again.
func minimumDeletions(word string, k int) int {
n := len(word)
freqs := make([]int, 26)
for i := range n {
freqs[word[i]-'a']++
}
slices.Sort(freqs)
ans := n
delLeft := 0
for i, freq := range freqs {
if freq == 0 {
continue
}
// Approach 1
delRight := 0
for _, freq2 := range freqs[i+1:] {
delRight += max(0, freq2-freq-k)
}
ans = min(ans, delLeft+delRight)
// Approach 2
delLeft += freq
}
return ans
}