Count all distinct pairs with difference equal to k | A simple PHP program to count pairs with difference k ; Pick all elements one by one ; See if there is a pair of this picked element ; Driver Code
< ? php function countPairsWithDiffK ( $ arr , $ n , $ k ) { $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = $ i + 1 ; $ j < $ n ; $ j ++ ) if ( $ arr [ $ i ] - $ arr [ $ j ] == $ k or $ arr [ $ j ] - $ arr [ $ i ] == $ k ) $ count ++ ; } return $ count ; } $ arr = array ( 1 , 5 , 3 , 4 , 2 ) ; $ n = count ( $ arr ) ; $ k = 3 ; echo " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " , countPairsWithDiffK ( $ arr , $ n , $ k ) ; ? >