Greatest number less than equal to B that can be formed from the digits of A | C ++ implementation of the approach ; Function to return the greatest number not gtreater than B that can be formed with the digits of A ; To store size of A ; To store the required answer ; Traverse from leftmost digit and place a smaller digit for every position . ; Keep all digits in A ; To avoid leading zeros ; For all possible values at ith position from largest value to smallest ; Take largest possible digit ; Keep duplicate of string a ; Remove the taken digit from s2 ; Sort all the remaining digits of s2 ; Add s2 to current s1 ; If s1 is less than B then it can be included in the answer . Note that stoll ( ) converts a string to lomg long int . ; change A to s2 ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string Permute_Digits ( string a , long long b ) { int n = a . size ( ) ; string ans = " " ; for ( int i = 0 ; i < n ; i ++ ) { set < char > temp ( a . begin ( ) , a . end ( ) ) ; if ( i == 0 ) temp . erase ( 0 ) ; for ( auto j = temp . rbegin ( ) ; j != temp . rend ( ) ; ++ j ) { string s1 = ans + * j ; string s2 = a ; s2 . erase ( s2 . find ( * j ) , 1 ) ; sort ( s2 . begin ( ) , s2 . end ( ) ) ; s1 += s2 ; if ( stoll ( s1 ) <= b ) { ans += * j ; a = s2 ; break ; } } } return ans ; } int main ( ) { string a = "123" ; int b = 222 ; cout << Permute_Digits ( a , b ) ; return 0 ; }