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
function findgroups ( arr , n ) { let c = [ 0 , 0 , 0 ] ; let i ; let 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 ) * Math . floor ( ( c [ 0 ] - 2 ) ) / 6 ) ; res += ( c [ 1 ] * ( c [ 1 ] - 1 ) * Math . floor ( ( c [ 1 ] - 2 ) ) / 6 ) ; res += ( Math . floor ( c [ 2 ] * ( c [ 2 ] - 1 ) * ( c [ 2 ] - 2 ) ) / 6 ) ; res += c [ 0 ] * c [ 1 ] * c [ 2 ] ; return res ; } let arr = [ 3 , 6 , 7 , 2 , 9 ] ; let n = arr . length ; document . write ( " " + findgroups ( arr , n ) ) ;