Skip to content

Commit 55d868b

Browse files
authored
2561. Rearranging Fruits.cpp [Solved]
2561. Rearranging Fruits.cpp
2 parents 3fc6e83 + 9248cb4 commit 55d868b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

2561. Rearranging Fruits.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
};

0 commit comments

Comments
 (0)