-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum.cpp
More file actions
64 lines (64 loc) · 1.66 KB
/
3sum.cpp
File metadata and controls
64 lines (64 loc) · 1.66 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<vector>
#include<algorithm>
#include<climits>
int solve(std::vector<int> &arr, int K){
std::sort(arr.begin(),arr.end());
//use three pointers approach
int distance = INT_MAX;
int returnValue;
int size = arr.size();
for(int i = 0;i<size;++i){
int sumLeft = K-arr[i];
//std::cout<<"Cscsdc";
//now find j, k such that
int j = 0, k = arr.size()-1;
while(j<k){
//std::cout<<"Cscsdc";
if(j!=i && k!=i){
int tempSum = arr[i] + arr[j] + arr[k];
if(tempSum>K){
if(distance>(tempSum-K)){
distance = tempSum-K;
returnValue = tempSum;
}
}
else if(tempSum<K){
if(distance>(K-tempSum)){
distance = K-tempSum;
returnValue = tempSum;
}
}
else{
return 0;
}
if(arr[j]+arr[k]<sumLeft){
++j;
}
else if(arr[j]+arr[k]>sumLeft){
--k;
}
}
else{
if(j==i){
++j;
}
if(k==i){
--k;
}
}
}
}
return returnValue;
}
int main(){
int N,K;
std::cin>>N>>K;
std::vector<int> vec(N);
for(int index = 0;index<N;++index){
std::cin>>vec[index];
}
int output = solve(vec,K);
std::cout<<output<<std::endl;
return 0;
}