Minimum and maximum number of digits required to be removed to make a given number divisible by 3 | Java program for the above approach ; Function to find the maximum and minimum number of digits to be removed to make str divisible by 3 ; Convert the string into array of digits ; Count of 0 s , 1 s , and 2 s ; Traverse the array ; Find the sum of digits % 3 ; Cases to find minimum number of digits to be removed ; Cases to find maximum number of digits to be removed ; Driver code ; Function Call
class GFG { static void minMaxDigits ( String str , int N ) { int arr [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) arr [ i ] = ( str . charAt ( i ) - '0' ) % 3 ; int zero = 0 , one = 0 , two = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) zero ++ ; if ( arr [ i ] == 1 ) one ++ ; if ( arr [ i ] == 2 ) two ++ ; } int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum = ( sum + arr [ i ] ) % 3 ; } if ( sum == 0 ) { System . out . print ( 0 + " ▁ " ) ; } if ( sum == 1 ) { if ( ( one != 0 ) && ( N > 1 ) ) System . out . print ( 1 + " ▁ " ) ; else if ( two > 1 && N > 2 ) System . out . print ( 2 + " ▁ " ) ; else System . out . print ( - 1 + " ▁ " ) ; } if ( sum == 2 ) { if ( two != 0 && N > 1 ) System . out . print ( 1 + " ▁ " ) ; else if ( one > 1 && N > 2 ) System . out . print ( 2 + " ▁ " ) ; else System . out . print ( - 1 + " ▁ " ) ; } if ( zero > 0 ) System . out . print ( N - 1 + " ▁ " ) ; else if ( one > 0 && two > 0 ) System . out . print ( N - 2 + " ▁ " ) ; else if ( one > 2 two > 2 ) System . out . print ( N - 3 + " ▁ " ) ; else System . out . print ( - 1 + " ▁ " ) ; } public static void main ( String [ ] args ) { String str = "12345" ; int N = str . length ( ) ; minMaxDigits ( str , N ) ; } }