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 mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.