Form smallest number using indices of numbers chosen from Array with sum less than S | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string max_number ( int arr [ ] , int sum ) { int frac [ 9 ] ; int maxi = INT_MIN ; string ans ; int pos ; for ( int i = 0 ; i < 9 ; i ++ ) { frac [ i ] = sum / arr [ i ] ; if ( frac [ i ] > maxi ) { pos = i ; maxi = frac [ i ] ; } } ans . insert ( 0 , string ( maxi , ( 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 [ i ] = ( j + '0' ) ; sum += arr [ pos ] - arr [ j - 1 ] ; break ; } } } if ( maxi == 0 ) { return 0 ; } else { return ans ; } } int main ( ) { int arr [ 9 ] = { 3 , 4 , 2 , 4 , 6 , 5 , 4 , 2 , 3 } ; int s = 13 ; cout << max_number ( arr , s ) ; return 0 ; }