Count of pairs with difference at most K with no element repeating | Java implementation to count the number of pairs whose difference is atmost K in an array ; Function to count the number of pairs whose difference is atmost K in an array ; Sorting the Array ; Variable to store the count of pairs whose difference is atmost K ; Loop to consider the consecutive pairs of the array ; if Pair found increment the index by 2 ; Driver Code ; Function Call
import java . util . * ; class GFG { static int countPairs ( int arr [ ] , int k ) { Arrays . sort ( arr ) ; int pair = 0 ; int index = 0 ; while ( index < arr . length - 1 ) { if ( arr [ index + 1 ] - arr [ index ] <= k ) { pair += 1 ; index += 2 ; } else { index += 1 ; } } return pair ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 4 , 3 , 7 , 5 } ; int k = 2 ; int count = countPairs ( arr , k ) ; System . out . println ( count ) ; } }