fork download
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3. class PairsLessThanK {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6.  
  7. // Read input values
  8. long n = sc.nextLong();
  9. long k = sc.nextLong();
  10. long[] b = new long[(int)n];
  11. for (int i = 0; i < n; i++) {
  12. b[i] = sc.nextLong();
  13. }
  14. long count = 0;
  15.  
  16. // Sort the array
  17. Arrays.sort(b);
  18.  
  19. // Two-pointer approach
  20. for (int i = 0, j = (int)n - 1; i < n; i++) {
  21. long d = b[i] + b[j];
  22. while(d>k && i!=j){
  23. j--;
  24. d = b[i] + b[j];
  25. }
  26. // if we have reached a point where i,j same then we would just be recounting.. so break
  27. // i we want <j
  28. if(i==j){
  29. break;
  30. }
  31. System.out.println(i + " " + j);
  32. count += (j - i);
  33. }
  34. System.out.println(count);
  35. }
  36. }
  37.  
Success #stdin #stdout 0.14s 60744KB
stdin
6 5 
1 2 3 4 5 6 
stdout
0 3
1 2
4