Problem · Array
Largest Number Below N from Reusable Digits
Learn this problemProblem statement
Given a positive integer n and a set of decimal digits digits, construct the largest non-negative integer that is strictly smaller than n and uses only digits from digits.
Each allowed digit may be reused any number of times. A multi-digit result cannot begin with zero, but the one-digit result 0 is valid. Return -1 when no valid result exists.
Function
largestNumberBelow(n: int, digits: int[]) → intExamples
Example 1
n = 23415digits = [2,4,9]return = 22999The prefix 23 cannot be continued with an allowed digit below 4, so the construction backtracks to 22 and fills the suffix with 9.
Example 2
n = 100digits = [0,1]return = 11No valid three-digit answer is below 100, so the best two-digit construction is 11.
Constraints
1 <= n <= 10^91 <= digits.length <= 100 <= digits[i] <= 9- All values in
digitsare distinct.