Given an array of integers, A1, A2, ..., An, including negatives and positives, and another integer S. Now we need to find three different integers in the array, whose sum is closest to the given integer S. If there exists more than one solution, any of them is ok.
You can assume all the integers are within int32_t range, and no arithmetic overflow will occur with calculating the sum. S is nothing special but a randomly picked number.
Is there any efficient algorithm other than brute force search to find the three integers?
Here is the program in java which is O(N^2)
Here is the C++ code:
I did this in n^3, my pseudocode is below;
//Create a hashMap with key as Integer and value as ArrayList //iterate through list using a for loop, for each value in list iterate again starting from next value;
//if the sum of arr[i] and arr[j] is less than desired sum then there is potential to find a third digit so do another for loop
//in this case we are now looking for the third value; if the sum of arr[i] and arr[j] and arr[k] is the desired sum then add these to the HashMap by making the arr[i] the key and then adding arr[j] and arr[k] into the ArrayList in the value of that key
after this you now have a dictionary that has all the entries representing the three values adding to the desired sum. Extract all these entries using HashMap functions. This worked perfectly.
Very simple N^2*logN solution: sort the input array, then go through all pairs Ai, Aj (N^2 time), and for each pair check whether (S - Ai - Aj) is in array (logN time).
Another O(S*N) solution uses classical dynamic programming approach.
In short:
Create an 2-d array V[4][S + 1]. Fill it in such a way, that:
V[0][0] = 1, V[0][x] = 0;
V1[Ai]= 1 for any i, V1[x] = 0 for all other x
V[2][Ai + Aj]= 1, for any i, j. V[2][x] = 0 for all other x
V[3][sum of any 3 elements] = 1.
To fill it, iterate through Ai, for each Ai iterate through the array from right to left.
John Feminella's solution has a bug.
At the line
We need to check if i,j,k are all distinct. Otherwise, if my target element is
6
and if my input array contains{3,2,1,7,9,0,-4,6}
. If i print out the tuples that sum to 6, then I would also get0,0,6
as output . To avoid this, we need to modify the condition in this way.This can be solved efficiently in O(n log (n)) as following. I am giving solution which tells if sum of any three numbers equal a given number.