Count valid pairs in the array satisfying given conditions | Java implementation of the approach ; Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer
class GFG { static int ValidPairs ( int arr [ ] , int n ) { int [ ] count = new int [ 121 ] ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] += 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) continue ; if ( Math . abs ( arr [ i ] - arr [ j ] ) % 2 == 1 ) continue ; ans += count [ arr [ i ] ] * count [ arr [ j ] ] ; if ( arr [ i ] == arr [ j ] ) ans -= count [ arr [ i ] ] ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 16 , 17 , 18 } ; int n = arr . length ; System . out . println ( ValidPairs ( arr , n ) ) ; } }