Search for a command to run...
Progressive hints first, then the full explanation and implementation when you're ready to cash out.
Review status
AI-generated and still unreviewed. Double-check the details before internalizing them.
Hints
Open only as much as you need to keep the solve alive.
The original order of the array is irrelevant. Pairs only care about values, so sort the array first.
After sorting, pairing a small number with a far-away large number is suspicious. It creates a big gap while also stealing numbers that could have paired locally.
Try sorted values . In an optimal answer, you can always make pair with without making the maximum difference worse.
Why? If is paired with and is paired with , replace those two pairs with and . The new pair differences are no larger than the old maximum.
So the optimal pairing is just adjacent pairs in sorted order: . The answer is the maximum of .
Sort the array. That is the whole trick.
Once the numbers are sorted as
we claim the best pairing is:
Then the answer is simply:
Why adjacent pairing is optimal
Look at the smallest remaining number, say .
Suppose some optimal solution pairs it with where . Then must be paired with some other number .
So the solution contains these two pairs:
Now replace them with:
This does not make the maximum pair difference worse:
So if there is an optimal solution where is not paired with , we can modify it into another optimal solution where they are paired. Nice little exchange argument, no drama.
After pairing with , the same logic applies to the remaining sorted numbers. Therefore, there is always an optimal solution that pairs adjacent sorted elements.
Algorithm
For each test case:
Complexity
Sorting dominates:
per test case, with total , so this is easily fine.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<ll> a(n);
for (ll &x : a) cin >> x;
sort(a.begin(), a.end());
ll ans = 0;
for (int i = 0; i < n; i += 2) {
ans = max(ans, a[i + 1] - a[i]);
}
cout << ans << '\n';
}
}#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<ll> a(n);
for (ll &x : a) cin >> x;
sort(a.begin(), a.end());
ll ans = 0;
for (int i = 0; i < n; i += 2) {
ans = max(ans, a[i + 1] - a[i]);
}
cout << ans << '\n';
}
}