fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. // Number of pairs whose diff <=K
  6. Scanner sc = new Scanner(System.in);
  7. int n = sc.nextInt();
  8. int k = sc.nextInt();
  9. int [] arr = new int[n];
  10.  
  11. for (int i = 0; i < n; i++) {
  12. arr[i] = sc.nextInt();
  13. }
  14. Arrays.sort(arr);
  15. int c = 0;
  16. int i=0;
  17. for (int j = 0; j < n; j++) {
  18. int diff = arr[j] - arr[i];
  19. while (diff > k) {
  20. i++;
  21. diff = arr[j] - arr[i];
  22. }
  23. c += (j - i + 1);
  24. }
  25.  
  26. System.out.println("Number of pairs whose diff <= "+k+" : "+ (c - n));
  27. sc.close();
  28. }
  29. }
  30.  
Success #stdin #stdout 0.19s 60964KB
stdin
3 2
1 3 2 
stdout
Number of pairs whose diff <= 2 : 3