Count all distinct pairs with difference equal to k | Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; arr [ r ] - arr [ l ] < k ; Driver Code
< ? php function countPairsWithDiffK ( $ arr , $ n , $ k ) { $ count = 0 ; sort ( $ arr ) ; $ l = 0 ; $ r = 0 ; while ( $ r < $ n ) { if ( $ arr [ $ r ] - $ arr [ $ l ] == $ k ) { $ count ++ ; $ l ++ ; $ r ++ ; } else if ( $ arr [ $ r ] - $ arr [ $ l ] > $ k ) $ l ++ ; else $ r ++ ; } 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 ) ; ? >