Problem Description
You are given two baskets (basket1 and basket2) containing n fruits each, where each fruit is represented by its cost. You can perform swap operations between any fruit from basket1 with any fruit from basket2. The cost of a swap is the minimum of the two fruit costs being swapped. The goal is to make the two baskets "equal" (i.e. after sorting both baskets, they should be identical) at a minimum total cost. If it is impossible to achieve, return -1.
Key Insights
- The total frequency (combined from both baskets) of each fruit must be even; otherwise, it is impossible to split evenly.
- Calculate the surplus fruits from one basket that need to be swapped out to balance both baskets.
- Use sorting to pair the smallest surplus fruit from one basket with the largest surplus fruit from the other, ensuring optimal swap costs.
- There is a trick: instead of directly swapping two fruits, sometimes it is cheaper to perform two swaps involving the smallest fruit overall (global minimum). Thus, for each swap pair, the effective cost is the minimum between:
- The direct swap cost, min(x, y)
- Indirect cost using the smallest fruit globally, which is 2 * globalMin
Space and Time Complexity
Time Complexity: O(n log n)
Space Complexity: O(n)
Solution
The solution begins by verifying if the transformation is possible. We combine the two baskets and count the frequencies. If any fruit has an odd combined frequency, the answer is -1. Next, we compute how many extra fruits each basket has (over the desired equal split) using frequency counts. We then sort the extra fruits from basket1 in ascending order and those from basket2 in descending order. For each pair of surplus fruits, we calculate the cost as the minimum between a direct swap (min(value1, value2)) and two swaps via the basket’s global minimum (2 * globalMin). The total cost accumulated is the minimal cost required to balance the baskets.
Code Solutions
Below are sample implementations in Python, JavaScript, C++, and Java.