2064. Minimized Maximum of Products Distributed to Any Store #830
-
Topics: You are given an integer You need to distribute all products to the retail stores following these rules:
Return the minimum possible Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a binary search on the maximum possible number of products assigned to any store ( Approach
Let's implement this solution in PHP: 2064. Minimized Maximum of Products Distributed to Any Store <?php
/**
* @param Integer $n
* @param Integer[] $quantities
* @return Integer
*/
function minimizedMaximum($n, $quantities) {
// Binary search on the possible values of `x`
$left = 1;
$right = max($quantities);
while ($left < $right) {
$mid = intval(($left + $right) / 2);
if (canDistribute($mid, $quantities, $n)) {
// If possible to distribute with `mid` as the maximum, try smaller values
$right = $mid;
} else {
// Otherwise, increase `mid`
$left = $mid + 1;
}
}
return $left;
}
/**
* Helper function to check if we can distribute products with maximum `x` per store
*
* @param $x
* @param $quantities
* @param $n
* @return bool
*/
function canDistribute($x, $quantities, $n) {
$requiredStores = 0;
foreach ($quantities as $quantity) {
// Calculate minimum stores needed for this product type
$requiredStores += ceil($quantity / $x);
// If we need more stores than available, return false
if ($requiredStores > $n) {
return false;
}
}
return $requiredStores <= $n;
}
// Test cases
echo minimizedMaximum(6, [11, 6]); // Output: 3
echo minimizedMaximum(7, [15, 10, 10]); // Output: 5
echo minimizedMaximum(1, [100000]); // Output: 100000
?> Explanation:
This approach minimizes |
Beta Was this translation helpful? Give feedback.
We can use a binary search on the maximum possible number of products assigned to any store (
x
). Here’s a step-by-step explanation and the PHP solution:Approach
Binary Search Setup:
left
) as 1 (since each store can get at least 1 product).right
) as the maximum quantity inquantities
array (in the worst case, one store gets all products of a type).x
(maximum products given to any store).Binary Search Logic:
x
, check if it’s feasible to distribute all products such that no store has more thanx
products.canDistribute(x)
to determine feasibility.Feasibility …