Розбір
Sort the programmers' ratings in the array . To find two programmers with the maximum total rating, we'll use the two-pointer technique.
Initialize the pointer at the beginning of the array and the pointer at the end of the array.
Among all possible sums , not exceeding , find the maximum. If , move the pointer forward. Otherwise, move the pointer backward. Continue this process until the pointers meet.
Example
Let’s consider the second test. Sort the numbers and initialize the pointers. Simulate the algorithm’s execution. In this case, : we are looking for two numbers with the maximum sum that does not exceed .
Algorithm realization
Read the input data.
scanf("%d %d", &n, &m); v.resize(n); for (i = 0; i < n; i++) scanf("%d", &v[i]);
Sort the programmers’ ratings.
sort(v.begin(), v.end());
Initialize the pointers. The variable stores the maximum sum of two elements.
int mx = -1, low = 0, high = n - 1;
The pointer is moved forward, and the pointer is moved backward.
while (low < high) {
Among all possible sums that do not exceed find the maximum. If , move forward. Otherwise, move backward.
if (v[low] + v[high] <= m) { mx = max(mx, v[low] + v[high]); low++; } else high--; }
Print the answer.
printf("%d\n", mx);