Counting the closest pair sums

Given n integers and a target v, count how many index pairs have a sum whose distance from v is as small as possible.

Medium5SortingTwo pointersArrayHash mapInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

You are given a sequence of nn integers a1,a2,,ana_1, a_2, \dots, a_n and an integer vv. Consider every pair (ai,aj)(a_i, a_j) of elements of the sequence with i<ji < j.

Among those pairs, find the ones whose sum ai+aja_i + a_j is closest to vv, that is, the pairs that minimize ai+ajv|a_i + a_j - v|, and print how many pairs reach that smallest distance. A sum equal to vv has distance 00.

Pairs are distinguished by position. Two pairs that hold the same values at different indices count separately.

Input

The first line contains nn.

The second line contains a1,a2,,ana_1, a_2, \dots, a_n, separated by spaces.

The third line contains vv.

Output

Print one integer, the number of pairs that satisfy the condition.

Constraints

  • 1<n1061 < n \le 10^6
  • 104ai104-10^4 \le a_i \le 10^4 for every ii
  • 104v104-10^4 \le v \le 10^4

Hint

In the example, no pair sums to v=12v = 12, but 1313 is reachable: 2+11=132 + 11 = 13, at distance 11 from vv. The sum 1111 is at distance 11 as well. Two pairs sum to 1111 (the value 22 with either copy of 99) and two pairs sum to 1313 (2+112 + 11 and 5+85 + 8), so the answer is 44. The sequence contains 99 twice, so the pair (2,9)(2, 9) is counted twice.