You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We have to make pairs of a[i], and b[j] such that the minimum value of |a[i] - b[j]| for all i and j is maximized
i and j belong from 0 to n-1
Explanation
We have to sort both the arrays
Our solution will be O(n^2)
Basically now, we'll go for every i from 0 to n-1
We'll create a minn variable, and initialize it with INT_MAX
Now, we'll go for every j from 0 to n-1
Now basically, we'll try to alternate it...if j<=i, we'll take the abs of the difference between a[j] and b[n+j-i-1] (ie. the value of b from i+1 to n-1)
And, if j>i, we'll take the abs of the difference between a[j] and b[j-i-1] (ie. the value of b from 0 to i-1)
Code (Important Part in C++)
int ans = 0;
forr(i, n) {
int minn = inf;
forr(j, n) {
// if (j == i) continue;if (j <= i) minn = min(minn, abs(a[j] - b[n + j - i - 1]));
else minn = min(minn, a[j] - abs(b[j - i - 1]));
}
ans = max(ans, minn);
}
Code (Full)
#include<bits/stdc++.h>usingnamespacestd;
#defineintlonglongusing pii = pair<int, int>;
#defineforr(i, n) for (int i = 0; i < n; i++)
#definereforr(i, n) for (int i = n; i >= 0; i--)
#defineeqforr(i, a, n) for (int i = a; i <= n; i++)
#definesqforr(i, n) for (int i = 1; i * i <= n; i++)
#definegenforr(i, a, b) for (int i = a; i < b; i++)
#definepba push_back
#definepopb pop_back
#definepopf pop_front
#defineallEle(x) (x).begin(), (x).end()
#defineallRle(x) (x).rbegin(), (x).rend()
typedef vector<int> vint;
typedef vector<string> vstr;
#definevcstr(vstr, n) forr(i, n) cin >> vstr[i]
#definevcin(vint, n) forr(i, n) cin >> vint[i]
#definevpin(vint) for (auto x : vint) cout << x << ""; cout << endl;
#definevpstr(vstr) for (auto x : vstr) cout << x << ""; cout << endl;
constint inf = 1e9 + 5;
voidsolve() {
int n;
cin >> n;
vint a(n);
vint b(n);
vcin(a, n);
vcin(b, n);
sort(allEle(a));
sort(allEle(b));
int ans = 0;
forr(i, n) {
int minn = inf;
forr(j, n) {
// if (j == i) continue;if (j <= i) minn = min(minn, abs(a[j] - b[n + j - i - 1]));
else minn = min(minn, a[j] - abs(b[j - i - 1]));
}
ans = max(ans, minn);
}
cout << ans << endl;
}
signedmain() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin >> t;
for (int i = 0; i < t; i++)
solve();
}