Form smallest number using indices of numbers chosen from Array with sum less than S | Java implementation to find minimum number which have a maximum length ; Function to find the minimum number which have maximum length ; Find Maximum length of number ; Find minimum number WHich have maximum length ; Driver Code
class GFG { static String max_number ( int arr [ ] , int sum ) { int frac [ ] = new int [ 9 ] ; int maxi = Integer . MIN_VALUE ; StringBuilder ans = new StringBuilder ( ) ; int pos = 0 ; for ( int i = 0 ; i < 9 ; i ++ ) { frac [ i ] = sum / arr [ i ] ; if ( frac [ i ] > maxi ) { pos = i ; maxi = frac [ i ] ; } } for ( int i = 0 ; i < maxi ; i ++ ) { ans . append ( ( char ) ( ( pos + 1 ) + '0' ) ) ; } sum -= maxi * arr [ pos ] ; for ( int i = 0 ; i < maxi ; i ++ ) { for ( int j = 1 ; j <= 9 ; j ++ ) { if ( sum + arr [ pos ] - arr [ j - 1 ] >= 0 ) { ans . setCharAt ( i , ( char ) ( j + '0' ) ) ; sum += arr [ pos ] - arr [ j - 1 ] ; break ; } } } if ( maxi == 0 ) { return "0" ; } else { return ans . toString ( ) ; } } public static void main ( String str [ ] ) { int arr [ ] = { 3 , 4 , 2 , 4 , 6 , 5 , 4 , 2 , 3 } ; int s = 13 ; System . out . println ( max_number ( arr , s ) ) ; } }