text: Minimum and maximum number of digits required to be removed to make a given number divisible by 3 | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void minMaxDigits ( string str , int N ) { int arr [ N ] ; for ( int i = 0 ; i < N ; i ++ ) arr [ i ] = ( str [ 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 ) { cout << 0 << ' ▁ ' ; } if ( sum == 1 ) { if ( one && N > 1 ) cout << 1 << ' ▁ ' ; else if ( two > 1 && N > 2 ) cout << 2 << ' ▁ ' ; else cout << -1 << ' ▁ ' ; } if ( sum == 2 ) { if ( two && N > 1 ) cout << 1 << ' ▁ ' ; else if ( one > 1 && N > 2 ) cout << 2 << ' ▁ ' ; else cout << -1 << ' ▁ ' ; } if ( zero > 0 ) cout << N - 1 << ' ▁ ' ; else if ( one > 0 && two > 0 ) cout << N - 2 << ' ▁ ' ; else if ( one > 2 two > 2 ) cout << N - 3 << ' ▁ ' ; else cout << -1 << ' ▁ ' ; } int main ( ) { string str = "12345" ; int N = str . length ( ) ; minMaxDigits ( str , N ) ; return 0 ; }