Counting the closest pair sums
InterviewTime limit2sMemory limit512 MB
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 integers and an integer . Consider every pair of elements of the sequence with .
Among those pairs, find the ones whose sum is closest to , that is, the pairs that minimize , and print how many pairs reach that smallest distance. A sum equal to has distance .
Pairs are distinguished by position. Two pairs that hold the same values at different indices count separately.
Input
The first line contains .
The second line contains , separated by spaces.
The third line contains .
Output
Print one integer, the number of pairs that satisfy the condition.
Constraints
- for every
Hint
In the example, no pair sums to , but is reachable: , at distance from . The sum is at distance as well. Two pairs sum to (the value with either copy of ) and two pairs sum to ( and ), so the answer is . The sequence contains twice, so the pair is counted twice.