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:
- Permutation of an array that has smaller values from another array
- Number of possible permutations when absolute difference between number of elements to the right and left are given
- Number of palindromic permutations | Set 1
- Generate all cyclic permutations of a number
- Find the number of good permutations
- Count the number of special permutations
- Largest number smaller than or equal to N divisible by K
- Largest smaller number possible using only one swap operation
- Find largest number smaller than N with same set of digits
- Find the closest and smaller tidy number
- Maximize the product of four factors of a Number
- Number of permutations of a string in which all the occurrences of a given character occurs together
- Number of unique permutations starting with 1 of a Binary String
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Largest number smaller than or equal to n and digits in non-decreasing order
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.