Given an array of unsorted integers a and a target, find a triplet in the array whose sum is closest to the target value. Return the sum of the triplet.
Example 1:
Input: a[] = [-2, -4, 6, 3, 7], target = 2
Output: 1
Explanation: Triplet with sum closest to target is [-2, -4, 7], sum of the triplets = 1
Example 2:
Input: a[] = [10, 2, 30, 49, 8], target = 50
Output: 48
Explanation: Triplet with sum closest to target is [10, 30, 8], sum of the triplets = 48
const threeSum = (arr, x) => {
let nums = [...arr].sort();
let smallestDiff = Number.MAX_VALUE;
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
let j = i + 1;
let k = nums.length - 1;
while (k > j) {
let sum = nums[i] + nums[j] + nums[k];
let currentDiff = x - sum;
if (currentDiff == 0) {
return sum;
}
if (Math.abs(currentDiff) < Math.abs(smallestDiff)) {
smallestDiff = currentDiff;
}
if (currentDiff > 0) {
j++;
} else {
k--;
}
}
}
console.log(x - smallestDiff);
return x - smallestDiff;
};
threeSum([10, 2, 30, 49, 8], 50);
threeSum([1, 0, 1, 1], 100);
Top comments (0)