-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClosest Three Sum
39 lines (38 loc) Β· 1.16 KB
/
Closest Three Sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
int threeSumClosest(vector<int> arr, int target) {
sort(arr.begin(),arr.end());
int x=INT_MAX;
int ans=INT_MIN;
for(int i=0;i<arr.size()-2;i++){
int l=i+1;
int r=arr.size()-1;
while(l<r){
if(target==(arr[i]+arr[l]+arr[r])){
return target;
}else if((arr[i]+arr[l]+arr[r])>target){
int y=abs((arr[i]+arr[l]+arr[r])-target);
if(x>y){
ans=(arr[i]+arr[l]+arr[r]);
x=y;
}else if(x==y){
ans=max(ans,(arr[i]+arr[l]+arr[r]));
x=y;
}
r--;
}else{
int y=abs((arr[i]+arr[l]+arr[r])-target);
if(x>y){
ans=(arr[i]+arr[l]+arr[r]);
x=y;
}else if(x==y){
ans=max(ans,(arr[i]+arr[l]+arr[r]));
x=y;
}
l++;
}
}
}
return ans;
}
};