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 int countValidPairs(int[] arr, int target) {
  11. int n = arr.length;
  12.  
  13. // Split into positive, negative, and zero buckets
  14. List<Integer> pos = new ArrayList<>();
  15. List<Integer> neg = new ArrayList<>();
  16. int zeroCount = 0;
  17.  
  18. for (int x : arr) {
  19. if (x > 0) pos.add(x);
  20. else if (x < 0) neg.add(x);
  21. else zeroCount++;
  22. }
  23.  
  24. Collections.sort(pos);
  25. Collections.sort(neg); // will be increasing (more negative to less negative)
  26.  
  27. int count = 0;
  28.  
  29. // ---------- Case 1: Both non-negative ----------
  30. if (target % 2 == 0) {
  31. int half = target / 2;
  32. int freqHalf = 0;
  33.  
  34. for (int x : pos) {
  35. if (x == half) freqHalf++;
  36. }
  37. if (zeroCount > 0 && half == 0) freqHalf += zeroCount; // include zeros
  38.  
  39. // All pairs (half, half)
  40. count += (freqHalf * (freqHalf - 1)) / 2;
  41. }
  42.  
  43. // ---------- Case 2: Both negative ----------
  44. if (target % 2 == 0) {
  45. int half = -target / 2;
  46. int freqHalf = 0;
  47.  
  48. for (int x : neg) {
  49. if (x == half) freqHalf++;
  50. }
  51.  
  52. // All pairs (half, half)
  53. count += (freqHalf * (freqHalf - 1)) / 2;
  54. }
  55.  
  56. // ---------- Case 3: One positive, one negative ----------
  57. if (target % 2 == 0) {
  58. int half = target / 2;
  59.  
  60. // Positive side: a[i] = half
  61. int freqHalfPos = 0;
  62. for (int x : pos) if (x == half) freqHalfPos++;
  63.  
  64. // Negative side: |a[j]| <= half
  65. int validNeg = 0;
  66. for (int x : neg) if (Math.abs(x) <= half) validNeg++;
  67.  
  68. count += freqHalfPos * validNeg;
  69.  
  70. // Negative side: a[j] = -half
  71. int freqHalfNeg = 0;
  72. for (int x : neg) if (x == -half) freqHalfNeg++;
  73.  
  74. // Positive side: |a[i]| < half
  75. int validPos = 0;
  76. for (int x : pos) if (Math.abs(x) < half) validPos++;
  77.  
  78. count += freqHalfNeg * validPos;
  79. }
  80.  
  81. // ---------- Case 4: One negative, one non-negative ----------
  82. // Already covered in Case 3 (since unordered pairs handled once)
  83.  
  84. return count;
  85. }
  86.  
  87. // Driver code
  88. public static void main(String[] args) {
  89. int[] arr = {2, -2, 4, -4, 3, -3, 0, 0};
  90. int target = 6;
  91.  
  92. int result = countValidPairs(arr, target);
  93. System.out.println("Number of valid unordered pairs: " + result);
  94. }
  95. }
Success #stdin #stdout 0.1s 53672KB
stdin
Standard input is empty
stdout
Number of valid unordered pairs: 3