Given two numbers N and M. Construct maximal number by permuting (changing order) the digits of N, not exceeding M.
Note : It is allowed to leave N as it is.
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
Approach : Let’s construct the answer digit by digit starting from the leftmost. We are asked to build lexicographically maximal answer. So in this order, we should choose the greatest digit on each step. The approach is to iterate over all possible digits starting from the greatest. For each digit check if it’s possible to put it in this position and compare the resulting number with number M. If it comes less than or equal to the value of M, then proceed to the next digit.
Below is the CPP implementation:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if digit cube limit of an integer arrives at fixed point or a limit cycle
- Sort a String in decreasing order of values associated after removal of values smaller than X
- Maximize number of groups formed with size not smaller than its largest element
- Maximum value with the choice of either dividing or considering as it is
- Compare two strings considering only alphanumeric characters
- Count the number of words having sum of ASCII values less than and greater than k
- Previous perfect square and cube number smaller than number N
- Find the largest number smaller than integer N with maximum number of set bits
- Maximize count of corresponding same elements in given permutations using cyclic rotations
- Largest number smaller than or equal to n and digits in non-decreasing order
- Largest number smaller than or equal to N divisible by K
- Find largest number smaller than N with same set of digits
- Print all permutations of a number N greater than itself
- Permutation of an array that has smaller values from another array
- Count of Binary Digit numbers smaller than N
- Print all Jumping Numbers smaller than or equal to a given value
- Euler's Totient function for all numbers smaller than or equal to n
- Sieve of Sundaram to print all primes smaller than n
- An interesting solution to get all prime numbers smaller than n
- Cube Free Numbers smaller than n
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.