You get an integer array nums and an integer target. Choose three numbers from three different positions in nums so that their sum lands as close to target as possible, and return that sum.
Every input is chosen so that exactly one sum is the closest. You will never have to pick between a sum just above target and another the same distance below it.
No three of these numbers make exactly 10. Both 6 + 1 + 4 and -2 + 9 + 4 make 11, one away, and no other choice gets that close.
Every possible sum is above -20, so the smallest one wins: -7 + 2 + 5 = 0.
0 + (-3) + 7 hits the target exactly.
Constraints
3 <= nums.length <= 500-1000 <= nums[i] <= 1000-10⁴ <= target <= 10⁴target.Trying every triple is O(n³), too slow at 500 numbers. Sort the array first: once the first number of the triple is fixed, the other two can be picked from the two ends of what is left.
The answer is a sum of three numbers, and you want the one with the smallest distance |sum - target|. The plain way is to compute every sum and keep the best. With 500 numbers that's about 2 · 10⁷ triples, and each one is checked from scratch.
Time O(n²)Space O(1)
The full walkthrough and code are part of Premium
11