#include <iostream>
#include <vector>
#include <algorithm> // std::sort
int threeSumClosest(std::vector<int>& nums, int target) {
std::sort(nums.begin(), nums.end()); // Sort the array
int closestSum = nums[0] + nums[1] + nums[2]; // Initialize with the first triplet sum
for (size_t i = 0; i < nums.size() - 2; i++) {
size_t left = i + 1, right = nums.size() - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
// Update closestSum if the current sum is closer to the target
if (std::abs(target - currentSum) < std::abs(target - closestSum)) {
closestSum = currentSum;
}
// Adjust pointers based on the comparison with the target
if (currentSum < target) {
++left;
} else {
--right;
}
}
}
return closestSum;
}
int main() {
std::vector<int> nums = {-1, 4, 2, 2};
int target = 4;
std::cout << "Closest sum: " << threeSumClosest(nums, target) << std::endl;
}
/*
run:
Closest sum: 3
*/