16 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
The idea with this one follows the same strategy as 15 3Sum (explanation is in there). The only difference now is that we are iterating towards a target value. Because we're dealing with how close the values are - the difference between the sum and the target value will give us the solution.
So to do this, I've maintained the minimum difference using a priority queue that pairs with the actual sum. Then I just return the top of the queue.
But I could have just as easily maintained the minimum within the algorithm in O(1) and O(1) space using a simple check.
Last updated