-
Notifications
You must be signed in to change notification settings - Fork 0
/
Closest Three Sum.cpp
70 lines (63 loc) · 1.63 KB
/
Closest Three Sum.cpp
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
65
66
67
68
69
70
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
// arr : given vector of elements
// target : given sum value
class Solution {
// -7 9 8 3 1 1
// 2
// -7 1 1 3 8 9
public:
int threeSumClosest(std::vector<int>& arr, int target) {
sort(arr.begin(), arr.end());
int prevDiff = INT_MAX;
int closestSum = INT_MIN;
for(int i = 0; i < arr.size() - 2; i++){
int start = i + 1;
int end = arr.size() - 1;
while(start < end){
int sum = arr[i] + arr[start] + arr[end];
if(sum == target) return sum;
int currentDiff = abs(sum - target);
if(currentDiff < prevDiff || (currentDiff == prevDiff && sum > closestSum)){
prevDiff = currentDiff;
closestSum = sum;
}
if(sum < target){
start++;
}
else{
end--;
}
}
}
return closestSum;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
cin.ignore();
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
int key;
cin >> key;
// cin.ignore();
// if (f)
// return 0;
Solution ob;
cout << ob.threeSumClosest(arr, key) << endl;
}
return 0;
}
// } Driver Code Ends