text: Count all possible groups of size 2 or 3 that have sum as multiple of 3 | C ++ Program to count all possible groups of size 2 or 3 that have sum as multiple of 3 ; Returns count of all possible groups that can be formed from elements of a [ ] . ; Create an array C [ 3 ] to store counts of elements with remainder 0 , 1 and 2. c [ i ] would store count of elements with remainder i ; To store the result ; Count elements with remainder 0 , 1 and 2 ; Case 3. a : Count groups of size 2 from 0 remainder elements ; Case 3. b : Count groups of size 2 with one element with 1 remainder and other with 2 remainder ; Case 4. a : Count groups of size 3 with all 0 remainder elements ; Case 4. b : Count groups of size 3 with all 1 remainder elements ; Case 4. c : Count groups of size 3 with all 2 remainder elements ; Case 4. c : Count groups of size 3 with different remainders ; Return total count stored in res ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int findgroups ( int arr [ ] , int n ) { int c [ 3 ] = { 0 } , i ; int res = 0 ; for ( i = 0 ; i < n ; i ++ ) c [ arr [ i ] % 3 ] ++ ; res += ( ( c [ 0 ] * ( c [ 0 ] - 1 ) ) >> 1 ) ; res += c [ 1 ] * c [ 2 ] ; res += ( c [ 0 ] * ( c [ 0 ] - 1 ) * ( c [ 0 ] - 2 ) ) / 6 ; res += ( c [ 1 ] * ( c [ 1 ] - 1 ) * ( c [ 1 ] - 2 ) ) / 6 ; res += ( ( c [ 2 ] * ( c [ 2 ] - 1 ) * ( c [ 2 ] - 2 ) ) / 6 ) ; res += c [ 0 ] * c [ 1 ] * c [ 2 ] ; return res ; } int main ( ) { int arr [ ] = { 3 , 6 , 7 , 2 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Required ▁ number ▁ of ▁ groups ▁ are ▁ " << findgroups ( arr , n ) << endl ; return 0 ; }