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. // your code goes here
  13. int[] arr = {3,2,1,5,4};
  14. int k =2;
  15. System.out.println("Number Of pairs with absolute diff k are " + cntPairs(arr,k));
  16. }
  17. public static int cntPairs(int[] arr, int k){
  18. HashMap<Integer,Integer> map = new HashMap<>();
  19. int res = 0;
  20. for(int i=0;i<arr.length;i++){
  21. if(map.containsKey(arr[i]-k)){
  22. res+=map.get(arr[i]-k);
  23. }
  24. if(map.containsKey(arr[i]+k)){
  25. res+=map.get(arr[i]+k);
  26. }
  27. map.put(arr[i],map.getOrDefault(arr[i],0)+1);
  28. }
  29. return res;
  30. }
  31. }
Success #stdin #stdout 0.15s 55704KB
stdin
Standard input is empty
stdout
Number Of pairs with absolute diff k are 3