Pairs with Difference less than K | PHP code to find count of Pairs with difference less than K . ; to sort the array . ; Keep incrementing result while subsequent elements are within limits . ; Driver code
< ? php function countPairs ( $ a , $ n , $ k ) { sort ( $ a ) ; $ res = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ j = $ i + 1 ; while ( $ j < $ n and $ a [ $ j ] - $ a [ $ i ] < $ k ) { $ res ++ ; $ j ++ ; } } return $ res ; } $ a = array ( 1 , 10 , 4 , 2 ) ; $ k = 3 ; $ n = count ( $ a ) ; echo countPairs ( $ a , $ n , $ k ) ; ? >