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?


int Solution::threeSumClosest(vector &A, int target) {
int n=A.size();
// 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;
sum = A[i] + A[start] + A[end];

                if (abs(target - sum) < abs(target - bestSum)) {
                    bestSum = sum;
                if (sum > target) {
                else {
return bestSum;



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


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.