Maximiza el valor de A reemplazando algunos de sus dígitos con dígitos de B

Dadas dos strings A y B que representan dos enteros, la tarea es imprimir el valor maximizado de A después de reemplazar 0 o más dígitos de A con cualquier dígito de  B.
Nota : un dígito en B solo se puede usar una vez.
Ejemplos: 
 

Entrada: A = “1234”, B = “4321” 
Salida: 4334 
1 puede ser reemplazado por 4 y 2 puede ser reemplazado por 3.
Entrada: A = “1002”, B = “100” 
Salida: 1102 
El primer 0 puede ser reemplazado por un 1. 
 

Enfoque: dado que el valor de A debe maximizarse, cualquier dígito será reemplazado solo por dígitos de mayor valor. Los dígitos de la izquierda tienen más importancia para contribuir al valor, por lo que deben reemplazarse con valores tan grandes como sea posible. Ordene B e itere de izquierda a derecha en A e intente reemplazar el dígito actual con el máximo de opciones disponibles si es posible.
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 maximized value of A
string maxValue(string a, string b)
{
    // Sort digits in ascending order
    sort(b.begin(), b.end());
    int n = a.length();
    int m = b.length();
 
    // j points to largest digit in B
    int j = m - 1;
    for (int i = 0; i < n; i++) {
 
        // If all the digits of b have been used
        if (j < 0)
            break;
 
        if (b[j] > a[i]) {
            a[i] = b[j];
 
            // Current digit has been used
            j--;
        }
    }
 
    // Return the maximized value
    return a;
}
 
// Driver code
int main()
{
    string a = "1234";
    string b = "4321";
 
    cout << maxValue(a, b);
 
    return 0;
}

Java

// Java implementation of the approach
  
import java.util.*;
 
class GFG{
 
// Function to return the maximized value of A
static String maxValue(char []a, char []b)
{
    // Sort digits in ascending order
    Arrays.sort(b);
    int n = a.length;
    int m = b.length;
 
    // j points to largest digit in B
    int j = m - 1;
    for (int i = 0; i < n; i++) {
 
        // If all the digits of b have been used
        if (j < 0)
            break;
 
        if (b[j] > a[i]) {
            a[i] = b[j];
 
            // Current digit has been used
            j--;
        }
    }
 
    // Return the maximized value
    return String.valueOf(a);
}
 
// Driver code
public static void main(String[] args)
{
    String a = "1234";
    String b = "4321";
 
    System.out.print(maxValue(a.toCharArray(), b.toCharArray()));
}
}
 
// This code is contributed by PrinciRaj1992

Python3

# Python3 implementation of the approach
 
# Function to return the maximized
# value of A
def maxValue(a, b):
     
    # Sort digits in ascending order
    b = sorted(b)
    bi = [i for i in b]
    ai = [i for i in a]
     
    n = len(a)
    m = len(b)
 
    # j points to largest digit in B
    j = m - 1
    for i in range(n):
 
        # If all the digits of b
        # have been used
        if (j < 0):
            break
 
        if (bi[j] > ai[i]):
            ai[i] = bi[j]
 
            # Current digit has been used
            j -= 1
         
    # Return the maximized value
    x = "" . join(ai)
    return x
 
# Driver code
a = "1234"
b = "4321"
 
print(maxValue(a, b))
 
# This code is contributed
# by mohit kumar

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
// Function to return the maximized value of A
static String maxValue(char []a, char []b)
{
    // Sort digits in ascending order
    Array.Sort(b);
    int n = a.Length;
    int m = b.Length;
 
    // j points to largest digit in B
    int j = m - 1;
    for (int i = 0; i < n; i++)
    {
 
        // If all the digits of b have been used
        if (j < 0)
            break;
 
        if (b[j] > a[i])
        {
            a[i] = b[j];
 
            // Current digit has been used
            j--;
        }
    }
 
    // Return the maximized value
    return String.Join("",a);
}
 
// Driver code
public static void Main(String[] args)
{
    String a = "1234";
    String b = "4321";
 
    Console.Write(maxValue(a.ToCharArray(), b.ToCharArray()));
}
}
 
// This code is contributed by PrinciRaj1992

PHP

<?php
// PHP implementation of the approach
 
// Function to return the maximized value of A
function maxValue($a, $b)
{
    // Sort digits in ascending order
    sort($b);
    $n = sizeof($a);
    $m = sizeof($b);
 
    // j points to largest digit in B
    $j = $m - 1;
    for ($i = 0; $i < $n; $i++)
    {
 
        // If all the digits of b have been used
        if ($j < 0)
            break;
 
        if ($b[$j] > $a[$i])
        {
            $a[$i] = $b[$j];
 
            // Current digit has been used
            $j--;
        }
    }
 
    // Convert array into string
    $a = implode("",$a);
     
    // Return the maximized value
    return $a ;
}
 
    // Driver code
    # convert string into array
    $a = str_split("1234");
    $b = str_split("4321");
 
    echo maxValue($a, $b);
     
// This code is contributed by Ryuga
?>

Javascript

<script>
// Javascript implementation of the approach
 
// Function to return the maximized value of A
function maxValue(a,b)
{
    // Sort digits in ascending order
    b.sort(function(x,y){return x-y;});
    let n = a.length;
    let m = b.length;
   
    // j points to largest digit in B
    let j = m - 1;
    for (let i = 0; i < n; i++) {
   
        // If all the digits of b have been used
        if (j < 0)
            break;
   
        if (b[j] > a[i]) {
            a[i] = b[j];
   
            // Current digit has been used
            j--;
        }
    }
   
    // Return the maximized value
    return (a).join("");
}
 
// Driver code
let a = "1234";
let b = "4321";
 
document.write(maxValue(a.split(""), b.split("")));
 
 
// This code is contributed by patel2127
</script>
Producción: 

4334

 

Complejidad de tiempo: O(n+m*log(m)) donde n es el tamaño de la string a y m es el tamaño de la string b.
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

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