[LeetCode] Fruits Into Baskets II

3477. Fruits Into Baskets II

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.

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
int res = 0;
vector<int> use(fruits.size());
for(auto& f : fruits) {
int at = -1;
for(int i = 0; i < baskets.size(); i++) {
if(use[i]) continue;
if(baskets[i] <= f) continue;
at = i;
break;
}
if(at == -1) res++;
else use[at] = 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/09/PS/LeetCode/fruits-into-baskets-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Related Issues not found

Please contact @SongHayoung to initialize the comment