-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
29 lines (29 loc) · 900 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public long minCost(int[] basket1, int[] basket2) {
int n = basket1.length;
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; ++i) {
cnt.merge(basket1[i], 1, Integer::sum);
cnt.merge(basket2[i], -1, Integer::sum);
}
int mi = 1 << 30;
List<Integer> nums = new ArrayList<>();
for (var e : cnt.entrySet()) {
int x = e.getKey(), v = e.getValue();
if (v % 2 != 0) {
return -1;
}
for (int i = Math.abs(v) / 2; i > 0; --i) {
nums.add(x);
}
mi = Math.min(mi, x);
}
Collections.sort(nums);
int m = nums.size();
long ans = 0;
for (int i = 0; i < m / 2; ++i) {
ans += Math.min(nums.get(i), mi * 2);
}
return ans;
}
}