Problem 376
Three Sum Closest
Medium · 20 pts · Array, Two Pointers, Sorting
Problem
Choose three elements from three different positions so that their sum is as close as possible to the target T. Print that sum. If two different sums are equally close to T (one above and one below), print the smaller one. Sort the array, fix the first element, and move two pointers over the rest, keeping track of the best sum seen so far.
Input
First line: N and T. Second line: N integers.
Output
Print the sum closest to T.
Constraints
3 <= N <= 1000; -1000 <= A[i] <= 1000; -10000 <= T <= 10000
Example input
4 1 -1 2 1 -4
Example output
2
Explanation
With T = 1 in -1 2 1 -4, the sum -1 + 2 + 1 = 2 is at distance 1 from the target, and no triplet sums to exactly 1 or 0, so the answer is 2.