File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+
2+
3+ class Solution {
4+ public:
5+ long long minCost (vector<int >& basket1, vector<int >& basket2) {
6+ unordered_map<int ,int > freq;
7+ for (int x : basket1) freq[x]++;
8+ for (int x : basket2) freq[x]--;
9+
10+ vector<int > extra1, extra2;
11+ int minFruit = INT_MAX;
12+
13+ // Collect unbalanced fruits
14+ for (auto [fruit, diff] : freq) {
15+ minFruit = min (minFruit, fruit);
16+ if (diff % 2 != 0 ) return -1 ; // impossible to balance
17+ int count = abs (diff) / 2 ;
18+ if (diff > 0 ) while (count--) extra1.push_back (fruit);
19+ else while (count--) extra2.push_back (fruit);
20+ }
21+
22+ sort (extra1.begin (), extra1.end ());
23+ sort (extra2.rbegin (), extra2.rend ());
24+
25+ long long cost = 0 ;
26+ for (int i = 0 ; i < extra1.size (); ++i) {
27+ cost += min ((long long )min (extra1[i], extra2[i]), 2LL * minFruit);
28+ }
29+ return cost;
30+ }
31+ };
You can’t perform that action at this time.
0 commit comments