Fruits Into Baskets II

easy array simulation binary search

Problem

You are given two equal-length arrays fruits and baskets. Going left to right, each fruit type must go into the leftmost still-free basket whose capacity is that fruit's quantity. Each basket holds only one fruit type; a fruit that fits nowhere stays unplaced. Return how many fruit types remain unplaced.

Inputfruits = [4, 2, 5], baskets = [3, 5, 4]
Output1
4 → basket[1]=5, 2 → basket[0]=3, 5 fits no free basket (basket[2]=4 too small). One unplaced → 1.

def numOfUnplacedFruits(fruits, baskets):
    n = len(fruits)
    used = [False] * n          # which baskets are taken
    unplaced = 0
    for q in fruits:            # each fruit type, left to right
        placed = False
        for j in range(n):      # scan for leftmost free fit
            if not used[j] and baskets[j] >= q:
                used[j] = True  # claim this basket
                placed = True
                break
        if not placed:
            unplaced += 1       # no basket could hold it
    return unplaced
function numOfUnplacedFruits(fruits, baskets) {
  const n = fruits.length;
  const used = new Array(n).fill(false); // taken baskets
  let unplaced = 0;
  for (const q of fruits) {              // each fruit, left to right
    let placed = false;
    for (let j = 0; j < n; j++) {        // leftmost free fit
      if (!used[j] && baskets[j] >= q) {
        used[j] = true;                  // claim this basket
        placed = true;
        break;
      }
    }
    if (!placed) unplaced++;             // nothing could hold it
  }
  return unplaced;
}
int numOfUnplacedFruits(int[] fruits, int[] baskets) {
    int n = fruits.length;
    boolean[] used = new boolean[n];     // taken baskets
    int unplaced = 0;
    for (int q : fruits) {               // each fruit, left to right
        boolean placed = false;
        for (int j = 0; j < n; j++) {    // leftmost free fit
            if (!used[j] && baskets[j] >= q) {
                used[j] = true;          // claim this basket
                placed = true;
                break;
            }
        }
        if (!placed) unplaced++;         // nothing could hold it
    }
    return unplaced;
}
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
    int n = fruits.size();
    vector<bool> used(n, false);          // taken baskets
    int unplaced = 0;
    for (int q : fruits) {               // each fruit, left to right
        bool placed = false;
        for (int j = 0; j < n; j++) {    // leftmost free fit
            if (!used[j] && baskets[j] >= q) {
                used[j] = true;          // claim this basket
                placed = true;
                break;
            }
        }
        if (!placed) unplaced++;         // nothing could hold it
    }
    return unplaced;
}
Time: O(n²) Space: O(n)