Question: We are going to solve a problem that s a slight variant of the 3 - Sum problem, in which we don t want to
We are going to solve a problem thats a slight variant of the Sum problem, in which we dont want
to find the pair that sums to the target T anymore, instead we want to find the pair such that their
sum is the closest to the target T but notice that it may NOT necessarily smaller than T and our
goal is to find this sum value which could be T itself and return it
More formally, the problem now is: given an array A of integers and Target T return the maximum
sum such that there exists i j k with Ai Aj Ak sum and the absolute value of the
difference between sum and T the smallest among all possible value of sum. Again here, the elements
in the array is not necessarily all positive numbers, and sum maybe smaller or bigger than T or even
T itself in this case, the difference between T and sum is
To solve this problem, we can adjust the original Sum problem by adding an additional variable to
track the minimum difference between a sum and T that we have seen so far, and at the end we just
return T minus that difference.
Complete the pseudocode below for this algorithm and give its running time: points
ThreeSumCloestAn T :
dif f infty
sort array An
for k to n do
i j k n
while i j do
sum
if sum T then
i
else if sum T then
j
else
return T
end if
if absT sum absdif f then
dif f T sum
end if
end while
return T dif f
The running time of this algorithm is in BigO format is fine.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
