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
function findSmallestNumberPossible ( N , K ) { if ( N > 45 * K ) { document . write ( " " ) ; return ; } var res = " " ; var count = 0 ; for ( var i = 9 ; i >= 1 ; ) { if ( count === K ) { i -- ; count = 0 ; } if ( N > i ) { N -= i ; res += String . fromCharCode ( " " . charCodeAt ( 0 ) + i ) ; } else { res += String . fromCharCode ( " " . charCodeAt ( 0 ) + N ) ; N = 0 ; break ; } count ++ ; } var ans = " " ; for ( var i = res . length - 1 ; i >= 0 ; i -- ) { ans += res [ i ] + " " ; } document . write ( ans ) ; } var N = 25 , K = 3 ; findSmallestNumberPossible ( N , K ) ;