[LeetCode] Rearranging Fruits

2561. Rearranging Fruits

You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want:

  • Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.
  • The cost of the swap is min(basket1[i],basket2[j]).

Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.

Return the minimum cost to make both the baskets equal or -1 if impossible.

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
30
31
class Solution {
public:
long long minCost(vector<int>& basket1, vector<int>& basket2) {
long long res = 0, mi = INT_MAX;
unordered_map<long long, pair<long long, long long>> freq;
for(auto b : basket1) freq[b].first += 1;
for(auto b : basket2) freq[b].second += 1;
map<long long, long long> req1, req2;
for(auto [k,v] : freq) {
mi = min(mi, k);
if((v.first + v.second) & 1) return -1;
if(v.first == v.second) continue;
auto [f,s] = v;
long long h = (f + s) / 2;
if(f > s) req1[k] += f - h;
else req2[k] += s - h;
}
if(req1.size() == 0) return 0;
for(auto i = begin(req1), j = prev(end(req2)); i != end(req1); i++) {
while(i->second) {
if(j->second == 0) j = prev(j);
else {
res += min({i->first, j->first, mi * 2});
i->second -= 1;
j->second -= 1;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/06/PS/LeetCode/rearranging-fruits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.