educative.io

Triplet Sum close to Target; why additional 'or' conditional statement while checking smallest_different against target_diff?

Oh! I realized the question is to find the smallest of the sum.

Thanks

Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/6210874538721280

Hi

  1. I am still confused on this part:

If there are more than one such triplet, return the sum of the triplet with the smallest sum.

Isn’t it supposed that if there are more than 1 triplet that both are at the same distance to target, all of them will have the same triplet sum? how would it be possible to get the smallest sum? maybe some sample cases could help understanding.
Update for my question 1:
I realized that this case would happen when we have a negative target and the sums that we are finding on every iteration are 2 negatives that are at the same distance to target, one to the left of target and another to the right of target (imagine the number line).

  1. I would appreciate your help on why would we do this second check on the if statement:

    …|| (Math.abs(targetDiff) == Math.abs(smallestDifference) && targetDiff > smallestDifference)){

So far I think the only possible case to enter this part is if both numbers are equal in numeric value but targetDiff is positive and smallestDifference negative, and I do not think it would be valid to update for that case. For example, lets say our target is -8 and our current closest difference is -10, if the next diff we find is 10, then the current smallest will be updated to that, but this new value would be farer from our target than with the previous value.

Thanks

checkout this thread