Encuentre la diferencia máxima después de aplicar las operaciones dadas dos veces en un número

Dado un número entero N , la tarea es encontrar la diferencia máxima después de aplicar la operación dada dos veces en el número entero dado. 

La operación se define de la siguiente manera:

  • Elija cualquier dígito (0-9) de N y reemplace todas las instancias del mismo dígito con cualquier otro dígito (0-9) .
  • N después de la operación no puede tener ceros a la izquierda y tampoco puede ser igual a cero.

Ejemplos:

Entrada: N = 777 
Salida: 888 
Explicación: seleccione el dígito 7 y reemplace todas sus ocurrencias con 9 para obtener 999. De manera similar, 111 se puede obtener reemplazando todas las ocurrencias de 7 con 1. Por lo tanto, la diferencia máxima posible es 888.

Entrada: N = 123456 
Salida: 820000 
Los números después de dos operaciones pueden ser 923456 y 103456. Por lo tanto, la diferencia máxima requerida es 820000. 

Explicación: La diferencia máxima se puede obtener mediante la resta del número máximo y mínimo que se puede obtener mediante la operación dada en N

  • El número máximo se puede obtener seleccionando el primer dígito de N de la izquierda que no es igual a ‘9’ y reemplazando todas las instancias de ese dígito en ‘9’ .
  • Encontrar el número mínimo es un poco complicado ya que N no puede tener ceros a la izquierda y tampoco puede ser igual a cero. Si el primer dígito de N desde la izquierda es ‘1’ , busque el primer dígito de la izquierda que sea mayor que ‘1’ y reemplace todas las instancias de ese dígito con ‘0’ .
  • De lo contrario, si el primer dígito de N desde la izquierda no es igual a ‘1’ , elija ese dígito y reemplace todas las instancias de ese dígito con ‘1’ .
  • Finalmente, devuelve la diferencia entre el número mínimo y máximo como respuesta.

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

C++

// C++ program to find the
// maximum difference
// after two given operations
// on a number
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns the
// maximum difference
// after two given operations
// on a number
int minDifference(int num)
{
    // Initialize the strings to make operations
    string maximum = to_string(num);
    string minimum = to_string(num);
 
    // Store length of the string
    int n = maximum.size();
 
    // Make the maximum number using
    // the first operation
    for (int i = 0; i < n; i++) {
        // Find the first digit which
        // is not equal to '9'
        if (maximum[i] != '9') {
            // Store the digit for
            // the given operation
            char digit = maximum[i];
            for (int j = i; j < n; j++) {
                // Replace all the selected
                // 'digit' with '9'
                if (maximum[j] == digit)
                    maximum[j] = '9';
            }
            // Break after the operation
            // is completed
            break;
        }
    }
    // Make the minimum number using
    // the second operation
 
    // Check if first digit is equal to '1'
    if (minimum[0] == '1') {
        for (int i = 1; i < n; i++) {
            // Find the first digit which
            // is greater than '1'
            if (minimum[i] - '0' > 1) {
                // Store the digit for
                // the given operation
                char digit = minimum[i];
                for (int j = i; j < n; j++) {
                    // Replace all the selected
                    // 'digit' with '0'
                    if (digit == minimum[j])
                        minimum[j] = '0';
                }
                // Break after the
                // operation is completed
                break;
            }
        }
    }
    else {
        // Select the first digit for
        // the given operation
        char digit = minimum[0];
        for (int i = 0; i < n; i++) {
            // Replace all the selected
            // 'digit' with '1'
            if (minimum[i] == digit)
                minimum[i] = '1';
        }
    }
    // Return the difference after
    // converting into integers
    return (stoi(maximum)
            - stoi(minimum));
}
 
// Driver Code
int main()
{
    int N = 1101157;
 
    cout << minDifference(N);
 
    return 0;
}

Java

// Java program to find the maximum
// difference after two given operations
// on a number
import java.util.*;
 
class GFG{
 
// Function that returns the
// maximum difference
// after two given operations
// on a number
static int minDifference(int num)
{
     
    // Initialize the strings to make operations
    StringBuilder maximum =
                  new StringBuilder(Integer.toString(num));
    StringBuilder minimum =
                  new StringBuilder(Integer.toString(num));
 
    // Store length of the string
    int n = maximum.length();
 
    // Make the maximum number using
    // the first operation
    for(int i = 0; i < n; i++)
    {
        
       // Find the first digit which
       // is not equal to '9'
       if (maximum.charAt(i) != '9')
       {
            
           // Store the digit for
           // the given operation
           char digit = maximum.charAt(i);
           for(int j = i; j < n; j++)
           {
                
              // Replace all the selected
              // 'digit' with '9'
              if (maximum.charAt(j) == digit)
                  maximum.setCharAt(j, '9');
           }
            
           // Break after the operation
           // is completed
           break;
       }
    }
     
    // Make the minimum number
    // using the second operation
    // Check if first digit is equal to '1'
    if (minimum.charAt(0) == '1')
    {
        for(int i = 1; i < n; i++)
        {
            
           // Find the first digit which
           // is greater than '1'
           if (minimum.charAt(i) - '0' > 1)
           {
                
               // Store the digit for
               // the given operation
               char digit = minimum.charAt(i);
               for(int j = i; j < n; j++)
               {
                    
                  // Replace all the selected
                  // 'digit' with '0'
                  if (digit == minimum.charAt(j))
                      minimum.setCharAt(j, '0');
               }
                
               // Break after the
               // operation is completed
               break;
           }
        }
    }
    else
    {
         
        // Select the first digit for
        // the given operation
        char digit = minimum.charAt(0);
        for(int i = 0; i < n; i++)
        {
            
           // Replace all the selected
           // 'digit' with '1'
           if (minimum.charAt(i) == digit)
               minimum.setCharAt(i, '1');
        }
    }
     
    // Return the difference after
    // converting into integers
    return (Integer.parseInt(maximum.toString()) -
            Integer.parseInt(minimum.toString()));
}
 
// Driver code
public static void main(String[] args)
{
    int N = 1101157;
 
    System.out.println(minDifference(N));
}
}
 
// This code is contributed by offbeat

Python3

# Python3 program to find the
# maximum difference after
# two given operations
# on a number
 
# Function that returns the
# maximum difference after 
# two given operations
# on a number
def minDifference(num):
     
    # Initialize the strings to
    # make operations
    maximum = list(str(num));
    minimum = list(str(num));
 
    # Store length of the string
    n = len(maximum);
 
    # Make the maximum number using
    # the first operation
    for i in range(n):
         
        # Find the first digit which
        # is not equal to '9'
        if (maximum[i] != '9'):
             
            # Store the digit for
            # the given operation
            digit = maximum[i];
             
            for j in range(i, n):
                 
                # Replace all the selected
                # 'digit' with '9'
                if (maximum[j] == digit):
                    maximum[j] = '9';
 
            # Break after the operation
            # is completed
            break;
 
    # Make the minimum number using
    # the second operation
    # Check if first digit is equal to '1'
    if (minimum[0] == '1'):
        for i in range(1, n):
             
            # Find the first digit which
            # is greater than '1'
            if (ord(minimum[i]) - ord('0') > 1):
                 
                # Store the digit for
                # the given operation
                digit = minimum[i];
                for j in range(i, n):
                     
                    # Replace all the selected
                    # 'digit' with '0'
                    if (digit == minimum[j]):
                        minimum[j] = '0';
                 
                # Break after the
                # operation is completed
                break;
         
    else :
         
        # Select the first digit
        # for the given operation
        digit = minimum[0];
        for i in range(n):
             
            # Replace all the selected
            # 'digit' with '1'
            if (minimum[i] == digit):
                minimum[i] = '1';
     
    maximum = "".join(maximum)
    minimum = "".join(minimum)
     
    # Return the difference after
    # converting into integers
    return (int(maximum) - int(minimum));
 
# Driver Code
if __name__ == "__main__":
 
    N = 1101157;
     
    print(minDifference(N));
 
# This code is contributed by AnkitRai01

C#

// C# program to find the maximum
// difference after two given
// operations on a number
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function that returns the
// maximum difference after
// two given operations on a
// number
static int minDifference(int num)
{
     
    // Initialize the strings to make operations
    char[] maximum = (num.ToString()).ToCharArray();
    char[] minimum = (num.ToString()).ToCharArray();
   
    // Store length of the string
    int n = maximum.Length;
   
    // Make the maximum number using
    // the first operation
    for(int i = 0; i < n; i++)
    {
         
        // Find the first digit which
        // is not equal to '9'
        if (maximum[i] != '9')
        {
             
            // Store the digit for
            // the given operation
            char digit = maximum[i];
            for(int j = i; j < n; j++)
            {
                 
                // Replace all the selected
                // 'digit' with '9'
                if (maximum[j] == digit)
                    maximum[j] = '9';
            }
             
            // Break after the operation
            // is completed
            break;
        }
    }
     
    // Make the minimum number using
    // the second operation
   
    // Check if first digit is equal to '1'
    if (minimum[0] == '1')
    {
        for(int i = 1; i < n; i++)
        {
             
            // Find the first digit which
            // is greater than '1'
            if (minimum[i] - '0' > 1)
            {
                 
                // Store the digit for
                // the given operation
                char digit = minimum[i];
                for(int j = i; j < n; j++)
                {
                     
                    // Replace all the selected
                    // 'digit' with '0'
                    if (digit == minimum[j])
                        minimum[j] = '0';
                }
                 
                // Break after the
                // operation is completed
                break;
            }
        }
    }
    else
    {
         
        // Select the first digit for
        // the given operation
        char digit = minimum[0];
        for(int i = 0; i < n; i++)
        {
             
            // Replace all the selected
            // 'digit' with '1'
            if (minimum[i] == digit)
                minimum[i] = '1';
        }
    }
     
    // Return the difference after
    // converting into integers
    return Convert.ToInt32(string.Join("", maximum)) -
           Convert.ToInt32(string.Join("", minimum));
}
 
// Driver Code
static void Main()
{
    int N = 1101157;
     
    Console.Write(minDifference(N));
}
}
 
// This code is contributed by divyesh072019

Javascript

<script>
 
// Javascript program to find the maximum
// difference after two given
// operations on a number
 
// Function that returns the
// maximum difference after
// two given operations on a
// number
function minDifference(num)
{
     
    // Initialize the strings to make operations
    let maximum = (num.toString()).split('');
    let minimum = (num.toString()).split('');
 
    // Store length of the string
    let n = maximum.length;
 
    // Make the maximum number using
    // the first operation
    for(let i = 0; i < n; i++)
    {
 
        // Find the first digit which
        // is not equal to '9'
        if (maximum[i] != '9')
        {
 
            // Store the digit for
            // the given operation
            let digit = maximum[i];
            for(let j = i; j < n; j++)
            {
 
                // Replace all the selected
                // 'digit' with '9'
                if (maximum[j] == digit)
                    maximum[j] = '9';
            }
 
            // Break after the operation
            // is completed
            break;
        }
    }
 
    // Make the minimum number using
    // the second operation
 
    // Check if first digit is equal to '1'
    if (minimum[0] == '1')
    {
        for(let i = 1; i < n; i++)
        {
 
            // Find the first digit which
            // is greater than '1'
            if (minimum[i].charCodeAt() -
                '0'.charCodeAt() > 1)
            {
 
                // Store the digit for
                // the given operation
                let digit = minimum[i];
                for(let j = i; j < n; j++)
                {
 
                    // Replace all the selected
                    // 'digit' with '0'
                    if (digit == minimum[j])
                        minimum[j] = '0';
                }
 
                // Break after the
                // operation is completed
                break;
            }
        }
    }
    else
    {
 
        // Select the first digit for
        // the given operation
        let digit = minimum[0];
        for(let i = 0; i < n; i++)
        {
 
            // Replace all the selected
            // 'digit' with '1'
            if (minimum[i] == digit)
                minimum[i] = '1';
        }
    }
 
    // Return the difference after
    // converting into integers
    return parseInt(maximum.join("")) -
           parseInt(minimum.join(""));
}
 
// Driver code
let N = 1101157;
  
document.write(minDifference(N));
 
// This code is contributed by suresh07
 
</script>
Producción: 

8808850

 

Publicación traducida automáticamente

Artículo escrito por rupesh_rao 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 *