Given two integers A and B, the task is to find the greatest number ≤ B that can be formed using all the digits of A.
Input: A = 123, B = 222
123, 132 and 213 are the only valid numbers which are ≤ 222.
213 is the maximum among them.
Input: A = 3921, B = 10000
Approach: Let’s construct the answer digit by digit starting from the leftmost. We need to build a lexicographically maximal answer so we should choose the greatest digit in each step.
Iterate over all possible digits starting from the greatest. For each digit check if it’s possible to put it in this position. For this, construct minimal suffix (greedily put the lowest digit) and compare the resulting number with B. If it is less than or equal to B then proceed to the next digit.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Greatest number that can be formed from a pair in a given Array
- Number formed by deleting digits such that sum of the digits becomes even and the number odd
- Find maximum number that can be formed using digits of a given number
- Find the largest number that can be formed by changing at most K digits
- Check if the number formed by the last digits of N numbers is divisible by 10 or not
- Recursive sum of digits of a number formed by repeated appends
- Find Nth even length palindromic number formed using digits X and Y
- Find all strings formed from characters mapped to digits of a number
- Find the Largest Cube formed by Deleting minimum Digits from a number
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Sum of digits equal to a given number in PL/SQL
- Find a number x such that sum of x and its digits is equal to given n.
- Find a Number X whose sum with its digits is equal to N
- Smallest number k such that the product of digits of k is equal to n
- Check if product of digits of a number at even and odd places is equal
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.
Improved By : sanjeev2552