Codeforces Round 920 (Div. 3) 1921D. Very Different Array Solution
Problem Link : https://codeforces.com/problemset/problem/1921/D
Solution in C++:
- /// Author : AH_Tonmoy
- #include <bits/stdc++.h>
- using namespace std;
- int32_t main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- int t;
- cin >> t;
- while (t--) {
- int n , m ; cin >> n >> m ;
- vector<int> a(n),b(m);
- for (int i = 0 ; i < n ; i++){
- cin >> a[i] ;
- }
- for ( int i = 0 ; i < m ; i++){
- cin >> b[i] ;
- }
- sort(a.begin(),a.end()) ;
- sort(b.rbegin(),b.rend()) ;
- int i = 0 , l = 0 , j = n - 1 , r = m - 1 ;
- long long ans = 0 ;
- int mx ;
- while(i <= j){
- int left = abs(a[i] - b[l]) ;
- int right = abs (a[j] - b[r]);
- int mx = max(left,right);
- ans += mx ;
- if ( left == mx ){
- i++ ;
- l++ ;
- }
- else{
- j--;
- r-- ;
- }
- }
- cout << ans <<'\n';
- }
- return 0 ;
- }
No comments