When for bestSum INT_MAX Is replaced by 10000000 then it print correct answers..other wise worng..whats the differece between INT_MAX and this large valuewhy?


#1

int Solution::threeSumClosest(vector &A, int target) {
int n=A.size();
sort(A.begin(),A.end());
// cout<<A[n-1]<<endl;
int bestSum=1000000000,sum=0;
for(int i=0;i<n-2;i++)
{
int start=i+1;
int end=n-1;
while(start<end)
{
sum = A[i] + A[start] + A[end];

                if (abs(target - sum) < abs(target - bestSum)) {
                    bestSum = sum;
                }
                if (sum > target) {
                    end--;
                }
                else {
                    start++;
                }
    }
}
return bestSum;

}


#2

Target may be a negative integer. So if you take bestSum as INT_MAX then (target - bestSum) may become less than INT_MIN.


#3

This seems to be working…however you could also use long long for variables holding summation, as i see sum of few numbers here exceeds the size of int.