Largest Number Below Limit
HardGreedy ยท TikTok
Given a non-negative integer limit written as a decimal string and a list digits of allowed digits, return the largest integer that is strictly less than limit and is written using only digits from digits. Digits may be reused any number of times, and the number has no leading zeros unless it is 0 itself. Return the result as a string, or "-1" if no such number exists.
Example 1
- Input:
- limit = "5230", digits = [0, 1, 2, 5]
- Output:
- "5225"
- Explanation
- The 3 in
5230is not allowed, so keep52, use 2 in the third place, then fill the rest with the largest digit, 5.
Example 2
- Input:
- limit = "1000", digits = [1, 9]
- Output:
- "999"
Example 3
- Input:
- limit = "10", digits = [0]
- Output:
- "0"
- Explanation
0is the only number that can be built, and it is allowed to be a single zero.
Constraints
1 <= limit.length <= 10^4limithas no leading zeros unless it is"0"1 <= digits.length <= 100 <= digits[i] <= 9