给定两个数N和M。通过排列(改变顺序)N的数字来构造最大数,但不超过M。 注: 它可以保持N的原样。 例如:
null
输入:N=123,M=222 产出:213 一共有3个!N=123的置换是可能的,但满足给定条件的唯一置换是213。类似地,在示例2中,总共有4个!N=3921的置换是可能的,但满足给定条件的唯一置换是9321。 输入:N=3921,M=10000 产出:9321
方法: 让我们从最左边开始逐位构造答案。我们被要求建造 词典编纂 最大答案。所以按照这个顺序,我们应该在每一步中选择最大的数字。方法是从最大值开始迭代所有可能的数字。对于每个数字,检查是否可以将其置于该位置,并将结果数字与数字M进行比较。如果小于或等于M的值,则转至下一个数字。 以下是CPP的实施:
CPP
// CPP program to Maximize the given number. #include <bits/stdc++.h> 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; // Swapping 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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END