Dado un entero positivo K y una string S que consta de N caracteres, la tarea es maximizar la suma de las frecuencias de exactamente K caracteres elegidos de la string dada.
Ejemplos:
Entrada: K – 3, S = ”GEEKSFORGEEKS”
Salida: 12
Explicación:
Elija el carácter E de la string S dada, la suma de la frecuencia de 3 E es 3*4 = 12, que es el máximo.Entrada: K = 10, S = ”GEEKSFORGEEKS”
Salida: 28
Enfoque: El problema dado se puede resolver usando el Enfoque Codicioso eligiendo aquellos K caracteres que tengan las frecuencias más altas. Siga los pasos a continuación para resolver el problema:
- Inicialice una variable, digamos suma a 0 que almacene la suma resultante de frecuencias de exactamente K caracteres elegidos de la string S .
- Encuentre las frecuencias de cada carácter en la string S y guárdelas en una array auxiliar, digamos freq[] .
- Ordene la array freq[] en orden descendente .
- Atraviese la array freq[] y realice lo siguiente:
- Si la frecuencia actual es menor que K , agregue freq[i]*freq[i] a la suma variable , ya que maximiza la suma resultante y disminuye el valor de freq[i] de K a medida que se eligen los caracteres freq[i] .
- De lo contrario, agregue el valor de K*freq[i] a la variable sum y salga del ciclo cuando se hayan elegido K caracteres.
- Después de completar los pasos anteriores, imprima el valor de la suma como resultado.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the maximum sum of // frequencies of the exactly K chosen // characters from the string S int maximumSum(string S, int N, int K) { // Stores the resultant maximum sum int sum = 0; // Stores the frequency of array // elements int freq[256] = { 0 }; // Find the frequency of character for (int i = 0; i < N; i++) { freq[int(S[i])]++; } // Sort the frequency array in the // descending order sort(freq, freq + 256, greater<int>()); // Iterate to choose K elements greedily for (int i = 0; i < 256; i++) { // If the freq[i] cards are // chosen if (K > freq[i]) { sum += freq[i] * freq[i]; K -= freq[i]; } // K cards have been picked else { sum += freq[i] * K; break; } } // Return the resultant sum return sum; } // Driver Code int main() { string S = "GEEKSFORGEEKS"; int K = 10; int N = S.length(); cout << maximumSum(S, N, K); return 0; }
Java
// Java program for the above approach import java.util.*; class GFG { // Function to find the maximum sum of // frequencies of the exactly K chosen // characters from the String S static int maximumSum(String S, int N, int K) { // Stores the resultant maximum sum int sum = 0; // Stores the frequency of array // elements Integer []freq = new Integer[256]; Arrays.fill(freq, 0); // Find the frequency of character for(int i = 0; i < N; i++) { freq[(int)S.charAt(i)] += 1; } // Sort the frequency array in the // descending order Arrays.sort(freq, Collections.reverseOrder()); // Iterate to choose K elements greedily for(int i = 0; i < 256; i++) { // If the freq[i] cards are // chosen if (K > freq[i]) { sum += freq[i] * freq[i]; K -= freq[i]; } // K cards have been picked else { sum += freq[i] * K; break; } } // Return the resultant sum return sum; } // Driver Code public static void main(String args[]) { String S = "GEEKSFORGEEKS"; int K = 10; int N = S.length(); System.out.print(maximumSum(S, N, K)); } } // This code is contributed by ipg2016107
Python3
# Python3 program for the above approach # Function to find the maximum sum of # frequencies of the exactly K chosen # characters from the string S def maximumSum(S, N, K): # Stores the resultant maximum sum sum = 0 # Stores the frequency of array # elements freq = [0] * 256 # Find the frequency of character for i in range(N): freq[ord(S[i])] += 1 # Sort the frequency array in the # descending order freq = sorted(freq)[::-1] # Iterate to choose K elements greedily for i in range(256): # If the freq[i] cards are # chosen if (K > freq[i]): sum += freq[i] * freq[i] K -= freq[i] # K cards have been picked else: sum += freq[i] * K break # Return the resultant sum return sum # Driver Code if __name__ == '__main__': S = "GEEKSFORGEEKS" K = 10 N = len(S) print(maximumSum(S, N, K)) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to find the maximum sum of // frequencies of the exactly K chosen // characters from the string S static int maximumSum(string S, int N, int K) { // Stores the resultant maximum sum int sum = 0; // Stores the frequency of array // elements int []freq = new int[256]; Array.Clear(freq, 0, 256); // Find the frequency of character for(int i = 0; i < N; i++) { freq[(int)S[i]]++; } // Sort the frequency array in the // descending order Array.Sort(freq); Array.Reverse(freq); // Iterate to choose K elements greedily for(int i = 0; i < 256; i++) { // If the freq[i] cards are // chosen if (K > freq[i]) { sum += freq[i] * freq[i]; K -= freq[i]; } // K cards have been picked else { sum += freq[i] * K; break; } } // Return the resultant sum return sum; } // Driver Code public static void Main() { string S = "GEEKSFORGEEKS"; int K = 10; int N = S.Length; Console.Write(maximumSum(S, N, K)); } } // This code is contributed by ipg2016107
Javascript
<script> // JavaScript program for the above approach // Function to find the maximum sum of // frequencies of the exactly K chosen // characters from the string S function maximumSum(S, N, K) { // Stores the resultant maximum sum let sum = 0; // Stores the frequency of array // elements let freq = Array.from({length: 256}, (_, i) => 0); // Find the frequency of character for(let i = 0; i < N; i++) { freq[S[i].charCodeAt()]++; } // Sort the frequency array in the // descending order freq.sort((a, b) => b - a); // Iterate to choose K elements greedily for(let i = 0; i < 256; i++) { // If the freq[i] cards are // chosen if (K > freq[i]) { sum += freq[i] * freq[i]; K -= freq[i]; } // K cards have been picked else { sum += freq[i] * K; break; } } // Return the resultant sum return sum; } // Driver Code let S = "GEEKSFORGEEKS"; let K = 10; let N = S.length; document.write(maximumSum(S.split(''), N, K)) </script>
Producción:
28
Complejidad temporal: O(N)
Espacio auxiliar: O(26)