const int inf = 0x3f3f3f;
const int x = []{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int ans=inf;
int diff = inf;
int result;
for(int i = 0; i < nums.size()-2; i++){
// if(i>0 && nums[i] > target) return ans;
// if(i>0 && nums[i]>target && nums[i]>0)
// return ans;
int l = i+1;
int r = nums.size() - 1;
while(l < r){
int s = nums[l] + nums[r] + nums[i];
int d = target- s;
if(d == 0) return target;
if(abs(d) < diff){
diff = abs(d);
ans = s;
}
if(l < r && s < target){
l++;
}
if(l < r && s > target){
r--;
}
}
}
return ans;
}
};