Rearranging Fruits Problem
Description
LeetCode Problem 2561.
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:
- Choose two indices
iandj, and swap thei^thfruit ofbasket1with thej^thfruit ofbasket2. - 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.
Example 1:
Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2]
Output: 1
Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal.
Example 2:
Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1]
Output: -1
Explanation: It can be shown that it is impossible to make both the baskets equal.
Constraints:
basket1.length == basket2.length1 <= basket1.length <= 10^51 <= basket1[i], basket2[i] <= 10^9
Solution
Approach: Greedy with a Cheapest-Fruit Detour
Count each cost in basket1 minus its count in basket2. If any difference is odd, the baskets can never match, so return -1. Otherwise half of each difference must move: the costs that basket1 has in excess (list a) must be swapped with those that basket2 has in excess (list b).
A direct swap of costs x and y costs min(x, y). Alternatively, use the cheapest fruit mi overall as a go-between: swap x with mi, then mi with y, for a total of 2 * mi. So each swap costs min(x, y, 2 * mi).
Merge a and b into one sorted list. The smallest half is always the cheaper side of the pairs, so add up min(nums[i], 2 * mi) over the first half.
Complexity: O(n log n) time and O(n) extra space.
class Solution:
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
cnt = Counter()
for a, b in zip(basket1, basket2):
cnt[a] += 1
cnt[b] -= 1
mi = min(cnt)
nums = []
for x, v in cnt.items():
if v % 2:
return -1
nums.extend([x] * (abs(v) // 2))
nums.sort()
m = len(nums) // 2
return sum(min(x, mi * 2) for x in nums[:m])