MetaOA #16
Find Pair Closest to K (for E5 :)
Estimated EasyJudge-ready
Topics (AI-labelled)Two Pointers
Given a non-decreasing array of positive integers, choose two different indices so that the absolute difference between the sum of their values and the target k is minimized. Output the two values in any order; if several answers are optimal, output any one of them. The same value can be chosen twice only if it appears at least twice in the array.
Input
This site's input: the first line contains n k (2≤n≤100000, −2147483648≤k≤2147483647); the second line contains n non-decreasing positive integers (1..2147483647). Use 64-bit integers for sums and differences.
Output
Output two integer values separated by a space. Swapping the order or outputting any other optimal pair is allowed; you do not have to match the example's exact form.
Example 1
Input:
7 35
5 8 14 17 25 40 43
Output:
8 25
Example 2
Input:
4 5
1 2 3 4
Output:
1 4
Example 3
Input:
3 4
2 2 9
Output:
2 2
Example notes
Example 1: 8 and 25 sum to 33, which is 2 away from 35, and no valid pair is closer; 25 8 is also accepted.
Example 2: 1 4 and 2 3 both sum to 5; either pair, in either order, is accepted.
Example 3: the array has two separate 2s, so 2 2 can be output, which hits the target 4 exactly.
Editorial
Loading solution…