Pairs with Difference less than K | Java 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
import java . io . * ; import java . util . Arrays ; class GFG { static int countPairs ( int a [ ] , int n , int k ) { Arrays . sort ( a ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j = i + 1 ; while ( j < n && a [ j ] - a [ i ] < k ) { res ++ ; j ++ ; } } return res ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 10 , 4 , 2 } ; int k = 3 ; int n = a . length ; System . out . println ( countPairs ( a , n , k ) ) ; } }