To understand this, instead of changing the minimum number of characters, let us preserve the maximum number of characters. We can see, that we can choose any of the distinct CC characters present, and preserve at most F = |S|/CF=∣S∣/C occurrences of each chosen character. It makes sense to choose the characters with maximal frequencies and try to preserve maximum characters. If we sort the character frequencies in decreasing order, it can be seen that its optimal to choose first min(C, D)min(C,D) (DD denote the number of distinct characters in initial string) characters and for each of these characters, preserve min(f, |S|/C)min(f,∣S∣/C) characters. The letters not preserved need to be replaced.
can’t understand this.