Given an array
nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Here is a Javascript Solution to the 3Sum Closest Problem from Leetcode:
const threeSum = (arr, sum) => {
const ilength = arr.length-2;
const jlength = ilength+1;
let total;
let closest = Infinity;
let diff = Math.abs(closest - sum);
for(let i=0, j=i+1, k=j+1; i<ilength; i++, j++, k++) {
total = arr[i]+arr[j]+arr[k];
if (diff > (Math.abs(total - sum))) {
closest = total;
if (closest === sum) {
break;
}
diff = Math.abs(closest - sum);
}
if (j<jlength) {
i--;
} else {
j=i+1;
}
if (k<arr.length) {
j--;
} else {
k=j+1
}
}
return closest;
}
Test Input
console.log(threeSum([-1, 0, 1, 2, -1, -4, -3, 5, -6, 0], 11))
Output
8
RUN THE CODE HERE: https://repl.it/@VinitKhandelwal/15-leetcode-3sum-closest
Comments
Post a Comment