var threeSumClosest = function (nums, target) {
/// [4, 0, 5, -5, 3, 3, 0, -4, -5], -2)
let sum = Number.MAX_SAFE_INTEGER;
let min_diff = Number.MAX_SAFE_INTEGER;
nums.sort((a, b) => a - b);
// -5, -5, -4, 0, 0, 3, 3, 4, 5 O(n^2)
for (let i = 0, j = 1, k = nums.length - 1; i < nums.length - 2; ++i){
while (j < k) {
const currSum = nums[i] + nums[j] + nums[k];
const diff = Math.abs(target - currSum);
if (diff < min_diff) {
min_diff = diff;
sum = currSum;
}
if (target === currSum) {
return target;
} else if (currSum < target) {
j++;
} else {
k--;
}
}
j = i + 2;
k = nums.length - 1;
}
return sum;
};