You are packaging medicine for shipment. You can choose exactly one container set and then must use containers only from that set to fulfill all customer orders.
Each container set defines the capacities of containers that are available in unlimited quantity. For a given order, you must:
capacity - order_amount
is considered
waste
for that order.
If, for some order, no container in a set is large enough, then that set cannot be used at all.
Your task is to evaluate all container sets and choose the one that:
If multiple container sets yield the same minimum total waste, return the smallest index among them. If no container set can satisfy all the orders, return -1.
You are given:
n
: the number of orders.
requirements[n]
: positive integers where
requirements[i]
is the required volume for the
i
-th order.
numContainerSets
: the number of distinct container sets.
containers[totalNumContainers][2]
describing all container sizes across all sets, where:
containers[k][0]
is the
set index
(an integer from
0
to
numContainerSets - 1
),
containers[k][1]
is a
container capacity
(a positive integer) belonging to that set.
Additional guarantees about containers:
You may assume reasonable constraints such as:
1 ≤ n ≤ 10^5
1 ≤ numContainerSets ≤ 10^5
1 ≤ totalNumContainers ≤ 10^5
1 ≤ requirements[i] ≤ 10^9
1 ≤ containers[k][1] ≤ 10^9
For a fixed container set s with capacities C_s and for an order of size r:
c
be the smallest capacity in
C_s
such that
c ≥ r
.
s
is
c - r
.
c
exists (i.e., all capacities in
C_s
are
< r
), then set
s
is
invalid
and cannot be used at all.
The total waste for set s is the sum of wastes over all orders in requirements.
Implement the following function (in any language):
int chooseContainers(int requirements[n],
int numContainerSets,
int containers[totalNumContainers][2])
Return value:
-1
.
Your algorithm should be efficient enough to handle inputs up to 10^5 in size; a naive solution that is or worse will time out.
n = 4
requirements = [4, 6, 6, 7]
numContainerSets = 3
containers = [
[0, 3], [0, 5], [0, 7], // set 0: capacities {3, 5, 7}
[1, 6], [1, 8], [1, 9], // set 1: capacities {6, 8, 9}
[2, 3], [2, 5], [2, 6] // set 2: capacities {3, 5, 6}
]
{3, 5, 7}
:
1 + 1 + 1 + 0 = 3
.
{6, 8, 9}
:
2 + 0 + 0 + 1 = 3
.
{3, 5, 6}
:
Both set 0 and set 1 are valid and yield total waste 3. Since we must return the smallest index among those, the correct answer is:
chooseContainers(...) = 0