Max count of N using digits of M such that 2 and 5 , and , 6 and 9 can be treated as same respectively | Java program for the above approach ; Function to find the count of numbers that can be formed using the given digits in the string ; Store the frequency of digits from the given string M ; Store length of the string M ; Loop to traverse the string ; Replace 5 with 2 ; Replace 9 with 6 ; Get the int form of the current character in the string ; Insert in the map ; Store all the digits of the required number N ; Loop to get all the digits from the number N ; Get the last digit as the remainder ; Replace 5 with 2 ; Replace 9 with 6 ; Insert the remainders in the rems map ; Store the resultant count ; Iterate through the rems map ; Get the key which is a digit from the number N to be formed ; If not present in the string M , number N that cannot be formed ; Divide the frequency of the digit from the string M with the frequency of the current remainder ; Choose the minimum ; Return the maximum count ; Driver Code
import java . util . HashMap ; import java . util . Map ; public class GFG { int solve ( int n , String str ) { HashMap < Integer , Integer > mymap = new HashMap < > ( ) ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = str . charAt ( i ) ; if ( c == '5' ) c = '2' ; else if ( c == '9' ) c = '6' ; int c_int = Integer . parseInt ( String . valueOf ( c ) ) ; if ( mymap . containsKey ( c_int ) ) mymap . put ( c_int , mymap . get ( c_int ) + 1 ) ; else mymap . put ( c_int , 1 ) ; } HashMap < Integer , Integer > rems = new HashMap < > ( ) ; while ( n > 0 ) { int rem = n % 10 ; if ( rem == 5 ) rem = 2 ; if ( rem == 9 ) rem = 6 ; if ( rems . containsKey ( rem ) ) rems . put ( rem , rems . get ( rem ) + 1 ) ; else rems . put ( rem , 1 ) ; n = n / 10 ; } int cnt = Integer . MAX_VALUE ; for ( Map . Entry < Integer , Integer > ele : rems . entrySet ( ) ) { int key = ele . getKey ( ) ; if ( ! mymap . containsKey ( key ) ) return 0 ; int temp = mymap . get ( key ) / ele . getValue ( ) ; cnt = Math . min ( cnt , temp ) ; } return cnt ; } public static void main ( String args [ ] ) { GFG obj = new GFG ( ) ; int N = 56 ; String M = "245769" ; System . out . println ( obj . solve ( N , M ) ) ; } }