Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active September 4, 2025 18:49
Show Gist options
  • Save tatsuyax25/49a31782c1f582f687d2a134c7542d91 to your computer and use it in GitHub Desktop.
Save tatsuyax25/49a31782c1f582f687d2a134c7542d91 to your computer and use it in GitHub Desktop.
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
/**
* Counts how many fruit types cannot be placed in any basket.
* Each fruit must go into the leftmost available basket with enough capacity.
* Each basket can hold only one fruit type.
*
* @param {number[]} fruits - Array of fruit quantities.
* @param {number[]} baskets - Array of basket capacities.
* @return {number} - Number of unplaced fruit types.
*/
var numOfUnplacedFruits = function(fruits, baskets) {
const n = baskets.length;
// Define block size for square root decomposition
const blockSize = Math.floor(Math.sqrt(n));
const blocks = [];
// Preprocess: build blocks array storing max capacity in each block
for (let i = 0; i < n; i += blockSize) {
const end = Math.min(i + blockSize, n);
let maxInBlock = -1;
for (let j = i; j < end; ++j) {
maxInBlock = Math.max(maxInBlock, baskets[j]);
}
blocks.push(maxInBlock);
}
let unplacedCount = 0;
// Try to place each fruit
for (const fruit of fruits) {
let basketFound = false;
// Scan blocks to find one with enough capacity
for (let i = 0; i < blocks.length; ++i) {
if (blocks[i] >= fruit) {
const start = i * blockSize;
const end = Math.min(start + blockSize, n);
// Scan individual baskets in the block
for (let j = start; j < end; ++j) {
if (baskets[j] >= fruit) {
// Place fruit in basket
baskets[j] = -1; // Mark basket as used
basketFound = true;
// Update block max after using this basket
let newMax = -1;
for (let k = start; k < end; ++k) {
newMax = Math.max(newMax, baskets[k]);
}
blocks[i] = newMax;
break; // Stop scanning baskets
}
}
}
if (basketFound) break; // Stop scanning blocks
}
if (!basketFound) {
unplacedCount++; // No basket found for this fruit
}
}
return unplacedCount;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment