Binary Search Approach Failing for larger test cases , help needed


#1
int num_lower_bs(int low,int high,vector<int>A, int num)
{
    if(A[low]>=num)   return low+1;
    else if(A[high]<num)   return high-1;
    while(low<=high)
    {
        int mid = (low+high)/2;
        if(A[mid]==num) return mid;
        if(A[mid]>num)
        {
            if(A[mid-1]<num)    return mid-1;
            high = mid-1;
        }
        else if(A[mid]<num)
        {
            if(A[mid+1]>num)    return mid;
            low = mid+1;
        }
    }
    return INT_MIN;
}

int Solution::threeSumClosest(vector<int> &A, int B) {
    sort(A.begin(),A.end());
    int n = A.size();
    int i=0;
    int k=n-1;
    long long int max_so_far=INT_MIN;
    while(k-i>=2)
    {
        int search = num_lower_bs(i,k,A, B - (A[i]+A[k]));
    
        if(search==i)  search++;
        else if(search==k)  search--;

        if(abs(B -(A[search]+A[i]+A[k])) < abs(B - max_so_far))  max_so_far = A[search]+A[i]+A[k];
        if (max_so_far==B)   return max_so_far;

        if (A[search]+A[i]+A[k]<B)    i++;
        else if(A[search]+A[i]+A[k]>B)    k--;
    }
    return max_so_far;
}

#2

typecast everything to long long


#3

Still partial,…