Sum of Two Numbers
InterviewTime limit1sMemory limit128 MB
Count the pairs of distinct given integers whose sum has the smallest absolute difference from K.
- Level
Medium5 of 10
- Topics
- Two pointers, Sorting
- Solved
- No attempts yet
Problem
You are given a set of distinct integers and another integer . Consider picking two distinct integers from and adding them; among all such pairs, look at the ones whose sum is closest to , meaning the absolute difference between the sum and is as small as possible.
For example, given the integers
the pair whose sum is closest to is alone (their sum is exactly ). For , the smallest possible difference between a pair's sum and is , achieved by five pairs: .
Given the integers and , write a program that counts how many pairs of two distinct integers have a sum closest to .
Input
Input is given on standard input. The first line contains the number of test cases . Each test case then consists of two lines.
The first line of each test case contains two integers and separated by a space (, ). The second line contains distinct integers separated by spaces, each between and inclusive.
Output
For each test case, output the result on its own line, in the order the test cases are given. Each line contains the number of pairs of two distinct integers whose sum is closest to .