-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
38 lines (30 loc) · 840 Bytes
/
Copy pathsolution.cpp
File metadata and controls
38 lines (30 loc) · 840 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
class Solution
{
public:
int sumDiffPairs(vector<int> &arr, int k)
{
// Sort the array so nearby elements have minimum differences
sort(arr.begin(), arr.end());
int ans = 0;
int n = arr.size();
// Start from the largest element
int i = n - 1;
while (i > 0)
{
// If adjacent elements form a valid pair
if (arr[i] - arr[i - 1] < k)
{
// Add both elements to answer
ans += arr[i] + arr[i - 1];
// Skip both because pairs must be disjoint
i -= 2;
}
else
{
// Current element cannot be paired optimally
i--;
}
}
return ans;
}
};