forked from 1laurelverma/DSA-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum_Closest.cpp
More file actions
43 lines (38 loc) · 809 Bytes
/
3Sum_Closest.cpp
File metadata and controls
43 lines (38 loc) · 809 Bytes
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
40
41
42
43
// Author : Chinmay Lohani
// Dated : 09.10.2022
// Timestatmp : 1665262265063
#include<bits/stdc++.h>
using namespace std;
int threeSumClosest(vector<int>& nums, int target) {
int n=nums.size(),ans=1e5;
sort(nums.begin(),nums.end());
for(int i=0;i<n;i++){
int l=i+1, r=n-1;
while(l<r){
int sum=nums[i]+nums[l]+nums[r];
if(sum==target){
return sum;
}
if(abs(sum-target)<abs(ans-target)){
ans=sum;
}
sum<target ? l++ : r--;
}
}
return ans;
}
int main()
{
vector<int> nums;
int n;
cin >> n;
while(n--) {
int temp;
cin >> temp;
nums.push_back(temp);
}
int target;
cin >> target;
cout << threeSumClosest(nums , target);
return 0;
}