Form smallest number using indices of numbers chosen from Array with sum less than S | Function to find the minimum number which have maximum length ; Find Maximum length of number ; Find minimum number WHich have maximum length ; Driver Code
function max_number ( arr , sum ) { let frac = new Array ( 9 ) ; let maxi = Number . MIN_VALUE ; let ans = [ ] ; let pos = 0 ; for ( let i = 0 ; i < 9 ; i ++ ) { frac [ i ] = Math . floor ( sum / arr [ i ] ) ; if ( frac [ i ] > maxi ) { pos = i ; maxi = frac [ i ] ; } } for ( let i = 0 ; i < maxi ; i ++ ) { ans . push ( String . fromCharCode ( ( pos + 1 ) + ' ' . charCodeAt ( 0 ) ) ) ; } sum -= maxi * arr [ pos ] ; for ( let i = 0 ; i < maxi ; i ++ ) { for ( let j = 1 ; j <= 9 ; j ++ ) { if ( sum + arr [ pos ] - arr [ j - 1 ] >= 0 ) { ans [ i ] = String . fromCharCode ( ( j + ' ' . charCodeAt ( 0 ) ) ) ; sum += arr [ pos ] - arr [ j - 1 ] ; break ; } } } if ( maxi == 0 ) { return " " ; } else { return ans . join ( " " ) ; } } let arr = [ 3 , 4 , 2 , 4 , 6 , 5 , 4 , 2 , 3 ] ; let s = 13 ; document . write ( max_number ( arr , s ) ) ;