Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 24, 2025 19:56
Show Gist options
  • Select an option

  • Save tatsuyax25/f9c63bba3f009c677888fcceffa0120b to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/f9c63bba3f009c677888fcceffa0120b to your computer and use it in GitHub Desktop.
You are given an array apple of size n and an array capacity of size m. There are n packs where the ith pack contains apple[i] apples. There are m boxes as well, and the ith box has a capacity of capacity[i] apples. Return the minimum number of box
/**
* @param {number[]} apple
* @param {number[]} capacity
* @return {number}
*/
var minimumBoxes = function(apple, capacity) {
// 1. Compute the total number of apples across all packs.
// Since aplles can be split across boxes, only the total matters.
let totalApples = 0;
for (let a of apple) {
totalApples += a;
}
// 2. Sort the box capacities in descending order.
// We want to use the largest boxes first to minimize the count.
capacity.sort((a, b) => b - a);
// 3. Greedily pick boxes until their combined capacity
// is enough to hold all apples.
let usedBoxes = 0;
let currentCapacity = 0;
for (let cap of capacity) {
currentCapacity += cap;
usedBoxes++;
// Once we have enough capacity, we can stop.
if (currentCapacity >= totalApples) {
return usedBoxes;
}
}
// 4. If we exit the loop without returning,
// it means even all boxes combined aren't enough.
// Some problems guarantee this won't happen, but we handle it anyway.
return usedBoxes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment