给定两个数字N和M。通过排列(改变顺序)N个数字构造最大数,不超过M。
注意:可以保留N不变。
例子:
Input : N = 123, M = 222
Output : 213
There are total 3! permutations possible for N = 123, But the only permutation that satisfies the given condition is 213. Similarly, In example 2, there are total 4! permutations possible for N = 3921, But the only permutation that satisfies the given condition is 9321.
Input : N = 3921, M = 10000
Output : 9321
方法:让我们从最左边开始逐位构造答案。我们被要求建立词典上的最大答案。因此,按此顺序,我们应该在每个步骤中选择最大的数字。方法是从最大的数字开始迭代所有可能的数字。对于每个数字,请检查是否可以将其放在此位置,并将结果数字与数字M进行比较。如果数字小于或等于M的值,则继续进行下一个数字。
以下是CPP的实现:
// CPP program to Maximize the given number.
#include
using namespace std;
// Function to maximize the number N with
// limit as M.
string maximizeNumber(string N, int M)
{
// Sorting the digits of the
// number in increasing order.
sort(N.begin(), N.end());
for (int i = 0; i < N.size(); i++)
for (int j = i + 1; j < N.size(); j++) {
// Copying the string into another
// temp string.
string t = N;
// Swaping the j-th char(digit)
// with i-th char(digit)
swap(t[j], t[i]);
// Sorting the temp string
// from i-th pos to end.
sort(t.begin() + i + 1, t.end());
// Checking if the string t is
// greater than string N and less
// than or equal to the number M.
if (stoll(t) > stoll(N) && stoll(t) <= M)
// If yes then, we will permanently
// swap the i-th char(or digit)
// with j-th char(digit).
swap(N[i], N[j]);
}
// Returns the maximized number.
return N;
}
// Driver function
int main()
{
string N = "123";
int M = 222;
cout << maximizeNumber(N, M) << endl;
return 0;
}
输出:
213