3477. Fruits Into Baskets II #2014
-
Topics: You are given two arrays of integers, From left to right, place the fruits according to these rules:
Return the number of fruit types that remain unplaced after all possible allocations are made. Example 1:
Since one fruit type remains unplaced, we return 1. Example 2:
Since all fruits are successfully placed, we return 0. Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of fruit types that remain unplaced after attempting to place each fruit type into the leftmost available basket that can accommodate it. The key challenge is efficiently matching each fruit to the earliest basket that meets the capacity requirement while ensuring each basket is used only once. Approach
Let's implement this solution in PHP: 3477. Fruits Into Baskets II <?php
/**
* @param Integer[] $fruits
* @param Integer[] $baskets
* @return Integer
*/
function numOfUnplacedFruits($fruits, $baskets) {
$n = count($fruits);
$taken = array_fill(0, $n, false);
$unplaced = 0;
foreach ($fruits as $fruit) {
$found = false;
for ($j = 0; $j < $n; $j++) {
if (!$taken[$j] && $baskets[$j] >= $fruit) {
$taken[$j] = true;
$found = true;
break;
}
}
if (!$found) {
$unplaced++;
}
}
return $unplaced;
}
// === Example usage ===
// Example 1:
$fruits1 = array(4, 2, 5);
$baskets1 = array(3, 5, 4);
$result1 = numOfUnplacedFruits($fruits1, $baskets1);
echo "Example 1 Output: " . $result1 . "\n"; // expected 1
// Example 2:
$fruits2 = array(3, 6, 1);
$baskets2 = array(6, 4, 7);
$result2 = numOfUnplacedFruits($fruits2, $baskets2);
echo "Example 2 Output: " . $result2 . "\n"; // expected 0
?> Explanation:
This approach efficiently matches each fruit to the earliest available basket, ensuring optimal placement while adhering to the problem constraints. The solution is straightforward and leverages direct simulation to achieve the desired outcome. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of fruit types that remain unplaced after attempting to place each fruit type into the leftmost available basket that can accommodate it. The key challenge is efficiently matching each fruit to the earliest basket that meets the capacity requirement while ensuring each basket is used only once.
Approach
fruits
andbaskets
, each of the same length. Each fruit must be placed in the leftmost basket that has sufficient capacity (i.e., the basket's capacity is at least the fruit's quantity) and is not already used. If no such basket is available, the fruit remains unplaced.