2561. Rearranging Fruits #2001
-
Topics: You have two fruit baskets containing
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 Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum cost required to make two fruit baskets equal by swapping fruits between them. The cost of each swap is defined as the minimum of the costs of the two fruits being swapped. If it's impossible to make the baskets equal, we should return -1. Approach
Let's implement this solution in PHP: 2561. Rearranging Fruits <?php
/**
* @param Integer[] $basket1
* @param Integer[] $basket2
* @return Integer
*/
function minCost($basket1, $basket2) {
$n = count($basket1);
$totalFreq = [];
for ($i = 0; $i < $n; $i++) {
$totalFreq[$basket1[$i]] = ($totalFreq[$basket1[$i]] ?? 0) + 1;
$totalFreq[$basket2[$i]] = ($totalFreq[$basket2[$i]] ?? 0) + 1;
}
foreach ($totalFreq as $count) {
if ($count % 2 != 0) {
return -1;
}
}
$m1 = min($basket1);
$m2 = min($basket2);
$m = min($m1, $m2);
$count1 = [];
foreach ($basket1 as $fruit) {
$count1[$fruit] = ($count1[$fruit] ?? 0) + 1;
}
$freq_swap = [];
foreach ($totalFreq as $fruit => $total_count) {
$c1 = $count1[$fruit] ?? 0;
$net = $c1 - intdiv($total_count, 2);
if ($net != 0) {
$freq_swap[$fruit] = abs($net);
}
}
$total_swap = 0;
foreach ($freq_swap as $count) {
$total_swap += $count;
}
$k = $total_swap / 2;
if ($k == 0) {
return 0;
}
$fruits_arr = array_keys($freq_swap);
sort($fruits_arr);
$ans = 0;
$remaining = $k;
foreach ($fruits_arr as $fruit) {
$count = $freq_swap[$fruit];
$take = min($count, $remaining);
$ans += $take * min($fruit, 2 * $m);
$remaining -= $take;
if ($remaining <= 0) {
break;
}
}
return $ans;
}
// Test cases
// Example 1
$basket1 = [4, 2, 2, 2];
$basket2 = [1, 4, 1, 2];
echo minCost($basket1, $basket2) . PHP_EOL; // Output: 1
// Example 2
$basket1 = [2, 3, 4, 1];
$basket2 = [3, 2, 5, 1];
echo minCost($basket1, $basket2) . PHP_EOL; // Output: -1?> Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to determine the minimum cost required to make two fruit baskets equal by swapping fruits between them. The cost of each swap is defined as the minimum of the costs of the two fruits being swapped. If it's impossible to make the baskets equal, we should return -1.
Approach
Frequency Analysis:
Global Minimum Fruit Cost:
m
) from both baskets. This value is crucial as it can be used to minimize the swap cost by acting as an intermedi…