Under construction

Still being built. Things may change

Counting the closest pair sums

Interview

Time limit2sMemory limit512 MB

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

Medium5 of 10

Topics
Sorting, Two pointers, Array, Hash map
Solved
No attempts yet

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+aj−v∣|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<n≤1061 < n \le 10^6
  • −104≤ai≤104-10^4 \le a_i \le 10^4 for every ii
  • −104≤v≤104-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.

Examples2

  1. Example 1

    Input
    9
    11 12 8 9 9 2 5 15 16
    12
    
    Expected output
    4
    
  2. Example 2

    Input
    2
    -10000 10000
    0
    
    Expected output
    1