K-Balanced Number
Time limit3sMemory limit1024 MB
Given X and K, find the largest number not above X whose most and least used digits (unused digits excluded) differ in count by at most K.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, String
- Solved
- No attempts yet
Problem
A decimal number is written using only the digits 0 through 9.
For a positive integer , look at the digits used to write in decimal, where does not start with 0. If the count of the most frequently used digit minus the count of the least frequently used digit is at most , then is called a -balanced number.
Given positive integers and , find the largest -balanced number that is less than or equal to .
Input
The first line contains the number of test cases .
Each of the next lines contains positive integers and , separated by a space.
In all test cases, the sum of the lengths of is at most .
Output
For each test case, print the answer on its own line, in input order.
Hints
- The input and output can exceed the range of a 64-bit integer.
- Digits that are not used are not counted.
- Python users are recommended to submit with PyPy.