Maximize the value of A by replacing some of its digits with digits of B in C++

C++Server Side ProgrammingProgramming

The task is to maximize the value of number A by replacing some of its digits with digits present in another number B. No digits will be replaced if A’s value cannot be maximized.

Note − a digit from B can be used only once.

Let’s now understand what we have to do using an example −

Input 

A = “1221”
B = “1211”

Output 

Maximum value of A possible 2221

Explanation − We here select 2 from B and replace it with the first 1 of A. Here it is the only choice as replacing any other digit of A with either 2 or 1 will not increase it’s value.

Input 

A = “1002”
B = “3200”

Output 

Maximum value of A possible 3202

Approach used in the below program as follows

  • Each of the digits in A will be replaced with a digit of B if it is less than that of B.

  • Sort the string B in ascending order.

  • Start traversing A from left.

  • Now traverse B from right.

  • Replace the digit in A with that of B if it is smaller and increment pointer at A and decrement pointer at B.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
// Function to return the maximized value of a
string valueup(string str1, string str2){
   // Sort digits in ascending order
   sort(str2.begin(), str2.end());
   int len1 = str1.length();
   int len2 = str2.length();
   int j = len2 - 1;
   for (int i = 0; i < len1; i++) {
      // If all the digits of b consumed
      if (j < 0)
         break;
      if (str2[j] > str1[i]) {
         str1[i] = str2[j];
         j--; //once digit used
      }
   }
   return str1;
}
// Driver code
int main(){
   string a = "1204";
   string b = "4521";
   cout << valueup(a, b);
   return 0;
}

Output

If we run the above code we will get the following output −

5424
raja
Published on 14-Aug-2020 07:36:06
Advertisements