My code-

the problem-https://leetcode.com/problems/3sum-closest/

Please correct my code only and send it.please also explain whwere i have gone wrong and what could have been a better approach for this probrlm

My code-

the problem-https://leetcode.com/problems/3sum-closest/

Please correct my code only and send it.please also explain whwere i have gone wrong and what could have been a better approach for this probrlm

you have consider 3 numbers which are consecutive

but 3 numbers can be anything from the array

Correct Approach

why is difference =INT_MAX

why cant the sum be less than the target because its not mentioned like that ,only the closest sum is asked for??

initially we assume the difference is infinity because we have to selected any 3 nos

sum can be less than target

then why have we kept this condition

if (sum <= target) j++;

` else k--;`

because if sum <= target then it means

to go closer to target we have to increase sum hence increase j (as array is sorted)

else if sum>target

to go closer to target we have to decrease sum hence decrease k (as array is sorted)

if the question would have been that select 3 nos such that the difference is max ,then would we have to write difference =INT_MAX there.

no then we consider the difference to be INT_MIN

ok,I have understood

is your doubt resolved?

if so then plz mark it as resolved

I hope I’ve cleared your doubt. I ask you to please rate your experience here

Your feedback is very important. It helps us improve our platform and hence provide you

the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen

the doubt.