Smallest number whose sum of digits is N and every digit occurring at most K times | Function to find the smallest number whose sum of digits is N and each digit occurring at most K times ; Maximum sum possible using each digit at most K times ; Append smallest number into the resultant string ; Iterate over the range [ 9 , 1 ] ; If the count of the digit is K , then update count and check for the next digit ; If N is greater than current digit ; Subtract i from N ; Insert i as a digit ; Insert remaining N as a digit ; Increment count ; Reverse the string ; Print the answer ; Driver Code ; Function Call
def findSmallestNumberPossible ( N , K ) : NEW_LINE INDENT if ( N > 45 * K ) : NEW_LINE INDENT print ( " - 1" , endl = " " ) ; NEW_LINE return ; NEW_LINE DEDENT res = " " ; NEW_LINE count = 0 ; NEW_LINE i = 9 ; NEW_LINE while i >= 1 : NEW_LINE INDENT if ( count == K ) : NEW_LINE INDENT i -= 1 ; NEW_LINE count = 0 ; NEW_LINE DEDENT if ( N > i ) : NEW_LINE INDENT N -= i ; NEW_LINE res += chr ( 48 + i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res += chr ( N + 48 ) ; NEW_LINE N = 0 ; NEW_LINE break ; NEW_LINE DEDENT count += 1 ; NEW_LINE DEDENT res = res [ : : - 1 ] NEW_LINE print ( res , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 25 ; K = 3 ; NEW_LINE findSmallestNumberPossible ( N , K ) ; NEW_LINE DEDENT