Problem Statement

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.

Assume that there will only be one solution

**Example:**given array S = {-1 2 1 -4},and target = 1.

The sum that is closest to the target is 2(-1 + 2 + 1 = 2)

Problem Link

3 Sum - InterviewBit

Code

typedef long long int ll;
int Solution::threeSumClosest(vector<int> &nums, int B) {
    
     int n = nums.size();
        sort(nums.begin(),nums.end());
        int res = INT_MAX;
        int diff = INT_MAX;
         int l = 0, r = n-1;
        
        for(int i=0;i<n;i++)
        {
            int l = i+1;
            int r = n-1;
            
            while(l<r)
            {
                ll sum = (ll)nums[l]+(ll)nums[r]+(ll)nums[i];
                
                if(sum==B)
                return B;
                
                if(sum<B)
                {
                    l++;
                }
                else
                   r--;
                   
                
                if(diff>abs(B-sum))
                {
                    diff = abs(B-sum);
                    res = sum;
                }
            }
        
        }
        
        return res;
}