fork download
  1. import java.util.*;
  2.  
  3. class Ideone {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int target1 = sc.nextInt();
  7. int target2 = sc.nextInt();
  8. int n = sc.nextInt();
  9.  
  10. int arr[] = new int[n];
  11. for (int i = 0; i < n; i++) {
  12. arr[i] = sc.nextInt();
  13. }
  14.  
  15. int count = 0;
  16. for (int k = 1; k < arr.length - 1; k++) {
  17. int leftCount = countPair(0, k - 1, arr, target1);
  18. int rightCount = countPair(k, arr.length - 1, arr, target2);
  19. count += (leftCount * rightCount);
  20. }
  21.  
  22. System.out.println(count);
  23. }
  24.  
  25. public static int countPair(int start, int end, int arr[], int k) {
  26. int totalCount = 0;
  27. while (start < end) {
  28. int sum = arr[start] + arr[end];
  29. if (sum > k) {
  30. totalCount+=(end-start);
  31. end--; // move right pointer
  32. } else {
  33. start++; // move left pointer
  34. }
  35. }
  36. return totalCount;
  37. }
  38. }
Success #stdin #stdout 0.19s 56672KB
stdin
3
5
5
1
2
3
4
5
stdout
2