fork download
  1. // A simple Java program to
  2. //count pairs with difference k
  3. import java.util.*;
  4. import java.io.*;
  5.  
  6. class GFG {
  7.  
  8. static int countPairsWithDiffK(int arr[],
  9. int n, int k)
  10. {
  11. int count = 0;
  12.  
  13. // Pick all elements one by one
  14. for (int i = 0; i < n; i++)
  15. {
  16. // See if there is a pair
  17. // of this picked element
  18. for (int j = i + 1; j < n; j++)
  19. if (arr[i] - arr[j] == k ||
  20. arr[j] - arr[i] == k)
  21. count++;
  22. }
  23. return count;
  24. }
  25.  
  26. // Driver code
  27. public static void main(String args[])
  28. {
  29. Scanner sc=new Scanner(System.in);
  30. int t=sc.nextInt();
  31. while(t>0){
  32.  
  33. int n = sc.nextInt();
  34. int k = sc.nextInt();
  35. int []arr=new int[n];
  36. for(int i=0;i<n;i++){
  37. arr[i]=sc.nextInt();
  38. }
  39. int diff=countPairsWithDiffK(arr, n, k);
  40. if(diff>0){
  41. System.out.println("YES");
  42. }
  43. else{
  44. System.out.println("NO");
  45. }
  46. t--;
  47. }
  48. }
  49. }
  50.  
  51.  
  52.  
Success #stdin #stdout 0.11s 49364KB
stdin
2
5 2
2 4 1 6 3
8 10
9 8 7 6 5 4 3 2	
stdout
YES
NO