Minimice la suma de valores ASCII después de eliminar todas las apariciones de un carácter

Dada la string str , la tarea es minimizar la suma de los valores ASCII de cada carácter de str después de eliminar cada aparición de un carácter en particular.

Ejemplos:

Entrada: str = “geeksforgeeks” 
Salida: 977 
‘g’ aparece dos veces -> 2 * 103 = 206 
‘e’ aparece 4 veces -> 4 * 101 = 404 
‘k’ aparece dos veces -> 2 * 107 = 214 
‘s’ ocurre dos veces -> 2 * 115 = 230 
‘f’ ocurre una vez -> 1 * 102 = 102 
‘o’ ocurre una vez -> 1 * 111 = 111 
‘r’ ocurre una vez -> 1 * 114 = 114 
Suma total = 1381 
In para minimizar la suma, elimine todas las ocurrencias de ‘e’ de la string 
Y la nueva suma se convierte en 1381 – 404 = 977
Entrada: str = “abcd” 
Salida: 294 

Acercarse: 

  1. Tome la suma de todos los valores ASCII en la string dada.
  2. Además, almacene las ocurrencias de cada uno de los caracteres de la string.
  3. Elimine todas las ocurrencias del carácter que contribuye con el valor máximo a la suma, es decir, cuya ocurrencia * ASCII es máxima.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimized sum
int getMinimizedSum(string str, int len)
{
    int i, maxVal = INT_MIN, sum = 0;
 
    // To store the occurrences of
    // each character of the string
    int occurrences[26] = { 0 };
    for (i = 0; i < len; i++) {
 
        // Update the occurrence
        occurrences[str[i] - 'a']++;
 
        // Calculate the sum
        sum += (int)str[i];
    }
 
    // Get the character which is contributing
    // the maximum value to the sum
    for (i = 0; i < 26; i++)
 
        // Count of occurrence of the character
        // multiplied by its ASCII value
        maxVal = max(maxVal, occurrences[i] * (i + 'a'));
 
    // Return the minimized sum
    return (sum - maxVal);
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    int len = str.length();
    cout << getMinimizedSum(str, len);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.Arrays;
import java.lang.Math;
 
class GfG
{
 
    // Function to return the minimized sum
    static int getMinimizedSum(String str, int len)
    {
        int i, maxVal = Integer.MIN_VALUE, sum = 0;
     
        // To store the occurrences of
        // each character of the string
        int occurrences[] = new int[26];
        Arrays.fill(occurrences, 0);
         
        for (i = 0; i < len; i++)
        {
     
            // Update the occurrence
            occurrences[str.charAt(i) - 'a']++;
     
            // Calculate the sum
            sum += (int)str.charAt(i);
        }
     
        // Get the character which is contributing
        // the maximum value to the sum
        for (i = 0; i < 26; i++)
     
            // Count of occurrence of the character
            // multiplied by its ASCII value
            maxVal = Math.max(maxVal, occurrences[i] * (i + 'a'));
     
        // Return the minimized sum
        return (sum - maxVal);
    }
 
    // Driver code
    public static void main(String []args){
         
        String str = "geeksforgeeks";
        int len = str.length();
        System.out.println(getMinimizedSum(str, len));
    }
}
 
// This code is contributed by Rituraj Jain

Python3

# Python3 implementation of the approach
import sys
 
# Function to return the minimized sum
def getMinimizedSum(string, length) :
 
    maxVal = -(sys.maxsize - 1)
    sum = 0;
 
    # To store the occurrences of
    # each character of the string
    occurrences = [0] * 26;
     
    for i in range(length) :
 
        # Update the occurrence
        occurrences[ord(string[i]) -
                    ord('a')] += 1;
 
        # Calculate the sum
        sum += ord(string[i]);
 
    # Get the character which is contributing
    # the maximum value to the sum
    for i in range(26) :
 
        # Count of occurrence of the character
        # multiplied by its ASCII value
        count = occurrences[i] * (i + ord('a'))
        maxVal = max(maxVal, count);
 
    # Return the minimized sum
    return (sum - maxVal);
 
# Driver code
if __name__ == "__main__" :
 
    string = "geeksforgeeks";
    length = len(string);
     
    print(getMinimizedSum(string, length));
 
# This code is contributed by Ryuga

C#

// C# implementation of the approach
using System;
 
class GfG
{
 
    // Function to return the minimized sum
    static int getMinimizedSum(string str, int len)
    {
        int i, maxVal = Int32.MinValue, sum = 0;
     
        // To store the occurrences of
        // each character of the string
        int [] occurrences = new int[26];
         
        for (i = 0; i < len; i++)
        {
     
            // Update the occurrence
            occurrences[str[i] - 'a']++;
     
            // Calculate the sum
            sum += (int)str[i];
        }
     
        // Get the character which is contributing
        // the maximum value to the sum
        for (i = 0; i < 26; i++)
     
            // Count of occurrence of the character
            // multiplied by its ASCII value
            maxVal = Math.Max(maxVal, occurrences[i] * (i + 'a'));
     
        // Return the minimized sum
        return (sum - maxVal);
    }
 
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        int len = str.Length;
        Console.WriteLine(getMinimizedSum(str, len));
    }
}
 
// This code is contributed by ihritik

Javascript

<script>
      // JavaScript implementation of the approach
      // Function to return the minimized sum
      function getMinimizedSum(str, len) {
        var i,
          maxVal = -2147483648,
          sum = 0;
 
        // To store the occurrences of
        // each character of the string
        var occurrences = new Array(26).fill(0);
 
        for (i = 0; i < len; i++) {
          // Update the occurrence
          occurrences[str[i].charCodeAt(0) - "a".charCodeAt(0)]++;
 
          // Calculate the sum
          sum += str[i].charCodeAt(0);
        }
 
        // Get the character which is contributing
        // the maximum value to the sum
        for (i = 0; i < 26; i++) {
          // Count of occurrence of the character
          // multiplied by its ASCII value
          maxVal = Math.max(maxVal, occurrences[i] * (i + "a".charCodeAt(0)));
        }
        // Return the minimized sum
        return sum - maxVal;
      }
 
      // Driver code
      var str = "geeksforgeeks";
      var len = str.length;
      document.write(getMinimizedSum(str, len));
    </script>
Producción: 

977

 

Publicación traducida automáticamente

Artículo escrito por Sumit bangar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *