fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13. int n = sc.nextInt();
  14. int arr []= new int[n];
  15.  
  16. for(int i=0;i<n;i++){
  17. arr[i] = sc.nextInt();
  18. }
  19. int k = sc.nextInt();
  20. int ans =0;
  21. HashMap<Integer,Integer> map = new HashMap<>();
  22.  
  23. map.put(arr[0],1);
  24.  
  25. for(int i=1;i<n;i++){
  26. int temp1 = arr[i] + k;
  27. int temp2 = arr[i] - k;
  28.  
  29. if(map.containsKey(temp1)){
  30. ans = ans + map.get(temp1);
  31. }
  32.  
  33. if(map.containsKey(temp2)){
  34. ans = ans + map.get(temp2);
  35. }
  36.  
  37. map.put(arr[i],map.getOrDefault(arr[i],0)+1);
  38. }
  39.  
  40.  
  41. System.out.println(ans);
  42. }
  43. }
Success #stdin #stdout 0.14s 54420KB
stdin
5
1 5 3 4 2
2
stdout
3