#C4546. Closest Pair with Sum Closest to Target

    ID: 48096 Type: Default 1000ms 256MiB

Closest Pair with Sum Closest to Target

Closest Pair with Sum Closest to Target

You are given an array of integers and a target sum \(S\). Your task is to find a pair of integers in the array such that the sum of the pair is as close as possible to \(S\). If there exists a pair whose sum exactly equals \(S\), then that pair is returned immediately. If the array does not have at least two elements, output nothing.

Note: The input array may contain duplicate elements. The answer should be printed as two space-separated integers to the standard output if a pair exists. Otherwise, print an empty line.

Hint: A common approach is to first sort the array and then use a two-pointer technique to find the optimal pair. Mathematically, you want to minimize \(|a+b-S|\) for a pair \((a,b)\).

inputFormat

The first line of input contains two integers \(N\) and \(S\), where \(N\) is the number of elements in the array and \(S\) is the target sum. The second line contains \(N\) space-separated integers representing the array.

Example:

5 54
10 22 28 29 30

outputFormat

If a valid pair exists (i.e., when \(N \ge 2\)), output the two integers separated by a space whose sum is closest to \(S\). If no such pair exists, output an empty line.

## sample
5 54
10 22 28 29 30
22 30