All problems

Problem 578

Count the Number of Fair Pairs

Medium · 20 pts · Array, Two Pointers, Binary Search, Sorting

Problem

A pair of indices i < j is fair if lower <= A[i] + A[j] <= upper. Count the fair pairs. Since the count does not depend on the order of the elements, sort the array first. Then the answer equals (number of pairs with sum <= upper) minus (number of pairs with sum <= lower - 1), and each of those counts takes one two-pointer pass. The answer can exceed 2^31.

Input

The first line contains N, lower and upper. The second line contains N integers.

Output

Print the number of fair pairs.

Constraints

1 <= N <= 100000; -10^9 <= A[i] <= 10^9; -10^9 <= lower <= upper <= 10^9

Example input

6 3 6
0 1 7 4 4 5

Example output

6

Explanation

For 0 1 7 4 4 5 with lower = 3 and upper = 6, the fair pairs are (0,4), (0,4), (0,5), (1,4), (1,4) and (1,5), using the two different 4s. So the answer is 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Sliding Window Median Next: Closest Pair of Points