Count maximum concatenation of pairs from given array that are divisible by 3 | C ++ program to implement the above approach ; Function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Stores count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Check if an element present in any pair or not ; Generate all possible pairs ; If the element already present in a pair ; If the element already present in a pair ; If concatenation of elements is divisible by 3 ; Update ans ; Mark i is True ; Mark j is True ; Driver Code ; To display the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDivBy3InArray ( int arr [ ] , int N ) { int ans = 0 ; bool taken [ N ] ; memset ( taken , false , sizeof ( taken ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( taken [ i ] == true ) { continue ; } for ( int j = i + 1 ; j < N ; j ++ ) { if ( taken [ j ] == true ) { continue ; } if ( stoi ( to_string ( arr [ i ] ) + to_string ( arr [ j ] ) ) % 3 == 0 || stoi ( to_string ( arr [ j ] ) + to_string ( arr [ i ] ) ) % 3 == 0 ) { ans += 1 ; taken [ i ] = true ; taken [ j ] = true ; } } } return ans ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 , 8 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDivBy3InArray ( arr , N ) ; return 0 ; }