-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sum_Pair_Closest_to_k.cpp
63 lines (58 loc) · 1.32 KB
/
Sum_Pair_Closest_to_k.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
//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution
{
public:
vector<int> sumClosest(vector<int> &arr, int k)
{
int i = 0;
int j = arr.size() - 1;
int nearestSum = INT_MAX;
vector<int> ans;
while (i < j)
{
int currentSum = arr[i] + arr[j];
if (abs(currentSum - k) < abs(nearestSum - k))
{
nearestSum = currentSum;
ans = {arr[i], arr[j]};
}
if (currentSum < k)
i++;
else
j--;
}
return ans;
}
};
//{ Driver Code Starts.
int main()
{
string ts;
getline(cin, ts);
int t = stoi(ts);
while (t--)
{
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number)
{
arr.push_back(number);
}
string ks;
getline(cin, ks);
int k = stoi(ks);
Solution ob;
vector<int> ans = ob.sumClosest(arr, k);
cout << ans[0] << " " << ans[1] << "\n";
}
return 0;
}
// } Driver Code Ends