#2561

Rearranging Fruits

expert · 1240 · lc hard +32 · verified · 57.5% accepted · 936 likes · top 53%

Description

You have two arrays basket1 and basket2 each containing n fruit costs. You may repeatedly swap the i-th fruit from basket1 with the j-th fruit from basket2; each swap costs min(basket1[i], basket2[j]). Two baskets are equal if their sorted versions are identical. Return the minimum total swap cost to equalize them, or -1 if it is 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.

Code

1
2
3