You are given two arrays of integers, fruits and baskets, each of length
n, where fruits[i] represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of the jth basket.
From left to right, place the fruits according to these rules:
Each fruit type must be placed in the leftmost available basket with a capacity greater than or equal to the quantity of that fruit type.
Each basket can hold only one type of fruit.
If a fruit type cannot be placed in any basket, it remains unplaced.
Return the number of fruit types that remain unplaced after all possible allocations are made.
Input: fruits =[3,6,1], baskets =[6,4,7]Output: 0Explanation:
*`fruits[0] = 3`is placed in`baskets[0] = 6`.*`fruits[1] = 6` cannot be placed in`baskets[1] = 4`(insufficient capacity) but can be placed in the next available basket,`baskets[2] = 7`.*`fruits[2] = 1`is placed in`baskets[1] = 4`.Since all fruits are successfully placed, we return0.
We want to place each fruit in the leftmost basket that can hold it, and each basket can be used only once. We can use a simple greedy approach, scanning baskets from left to right for each fruit and marking used baskets.
classSolution {
publicintunplacedFruits(int[] fruits, int[] baskets) {
boolean[] used =newboolean[baskets.length];
int ans = 0;
for (int f : fruits) {
boolean placed =false;
for (int j = 0; j < baskets.length; j++) {
if (!used[j]&& baskets[j]>= f) {
used[j]=true;
placed =true;
break;
}
}
if (!placed) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
fununplacedFruits(fruits: IntArray, baskets: IntArray): Int {
val used = BooleanArray(baskets.size)
var ans = 0for (f in fruits) {
var placed = falsefor (j in baskets.indices) {
if (!used[j] && baskets[j] >= f) {
used[j] = true placed = truebreak }
}
if (!placed) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defunplacedFruits(self, fruits: list[int], baskets: list[int]) -> int:
used = [False] * len(baskets)
ans =0for f in fruits:
placed =Falsefor j, b in enumerate(baskets):
ifnot used[j] and b >= f:
used[j] =True placed =Truebreakifnot placed:
ans +=1return ans