Ninja technique🥷 to ACE DSA Interviews.
abs(sum - target)
is less than the current closest difference and target sum abs(ans - target)
, we update the closest difference.ans
).
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
int n = nums.size();
sort(nums.begin(), nums.end());
int ans = nums[0] + nums[1] + nums[2];
for (int i = 0; i < n; ++i) {
int left = i + 1, right = n - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == target)
return target;
if (abs(sum - target) < abs(ans - target))
ans = sum;
if (sum < target)
++left;
else
--right;
}
}
return ans;
}
};