Practice › Greedy
Minimum Sum of Absolute Differences
Easy · Greedy · Asked at Amazon, TCS, Infosys, Wipro
Arrays A and B both have n elements. Pair every element of A with a different element of B so that the sum of |a − b| over all pairs is as small as possible. Print that sum.
Input
First line: n. Second line: array A. Third line: array B.
Output
The minimum sum.
Constraints
- 1 ≤ n ≤ 10^5
- −10^9 ≤ values ≤ 10^9
Sort both arrays and pair them in order — smallest with smallest. Crossing any two pairs can never reduce the sum. The total can pass 2^31.
Example 1
Input
3 4 1 8 2 3 6
Output
4
Example 2
Input
4 4 -1 7 4 8 0 -2 9
Output
11
Hints
- Try small cases: pairing in sorted order looks best.
- If two pairs cross (a1 < a2 but b1 > b2), swapping their partners never increases the sum.
Approach
Sort A and B and add |A[i] − B[i]| for every i. An exchange argument shows that any optimal pairing can be uncrossed without getting worse, and the only uncrossed pairing is the sorted one. Values reach 2 × 10^9 per pair, so the sum needs 64 bits.
Complexity: O(n log n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n), b(n);
for (auto &x : a) cin >> x;
for (auto &x : b) cin >> x;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
long long sum = 0;
for (int i = 0; i < n; i++) sum += llabs(a[i] - b[i]);
cout << sum << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = sorted(data[1 : 1 + n])
b = sorted(data[1 + n : 1 + 2 * n])
print(sum(abs(x - y) for x, y in zip(a, b)))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] a = new long[n], b = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
for (int i = 0; i < n; i++) {
in.nextToken();
b[i] = (long) in.nval;
}
Arrays.sort(a);
Arrays.sort(b);
long sum = 0;
for (int i = 0; i < n; i++) sum += Math.abs(a[i] - b[i]);
System.out.println(sum);
}
}Solve Minimum Sum of Absolute Differences online · All practice problems