任务是通过将某些数字替换为另一个数字B中的数字来最大化数字A的值。如果A的值无法最大化,则不会替换任何数字。
注意-来自B的数字只能使用一次。
现在让我们使用示例了解我们必须做的事情-
输入值
A = “1221” B = “1211”
输出结果
Maximum value of A possible 2221
说明-我们在这里从B中选择2并将其替换为A的前1个。这是唯一的选择,因为用2或1替换A的任何其他数字不会增加它的值。
输入值
A = “1002” B = “3200”
输出结果
Maximum value of A possible 3202
如果A中的每个数字小于B,则将替换为B。
按升序对字符串B进行排序。
从左开始遍历A。
现在,从右侧遍历B。
如果A中的数字较小,则用B中的数字替换,并在A处递增指针,在B处递减指针。
#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;
}输出结果
如果运行上面的代码,我们将获得以下输出-
5424