fork download
  1.  
  2. class unorderedpairs{
  3. public static int countPairs(int[] arr, int target) {
  4. if (target % 2 != 0) return 0;
  5. int k=target/2;
  6. int countless=0;
  7. int count=0;
  8. for (int num : arr){
  9. num=Math.abs(num);
  10. if (num==k) count++;
  11. else if(num<k) countless++;
  12. //|a[i]| < K and |a[j]| < K
  13. /*
  14.   max(|a[i]|, |a[j]|) < K
  15.   2 * max < target
  16.   → equation fails
  17.   */
  18. }
  19. //All elements equal to k can pair with each other, not with themselves, and only once (no reverse order).
  20. return count*countless+(count*(count-1))/2;
  21.  
  22. }
  23. public static void main(String[] args) {
  24. int[] arr = {1, -2, 3, -3, 2};
  25. int target = 6;
  26.  
  27. System.out.println(countPairs(arr, target));
  28. }
  29. }
Success #stdin #stdout 0.11s 52524KB
stdin
Standard input is empty
stdout
7