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:
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.
- Greatest number that can be formed from a pair in a given Array
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Find maximum product of digits among numbers less than or equal to N
- Highest and Smallest power of K less than and greater than equal to N respectively
- Print a number strictly less than a given number such that all its digits are distinct.
- 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
- Smallest even digits number not less than N
- Smallest odd digits number not less than N
- Largest number with maximum trailing nines which is less than N and greater than N-D
- Largest number less than N with digit sum greater than the digit sum of N
- Find the largest number that can be formed by changing at most K digits
- Highest power of 2 less than or equal to given number
- Sum of largest prime factor of each number less than equal to n
- Find Largest Special Prime which is less than or equal to a given number
- Count number of integers less than or equal to N which has exactly 9 divisors
- Largest number less than or equal to N/2 which is coprime to N
- Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
- Largest number less than or equal to Z that leaves a remainder X when divided by Y
- Find all powers of 2 less than or equal to a given number
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.
Improved By : sanjeev2552