Medium
You are given an integer n
indicating there are n
specialty retail stores. There are m
product types of varying amounts, which are given as a 0-indexed integer array quantities
, where quantities[i]
represents the number of products of the ith
product type.
You need to distribute all products to the retail stores following these rules:
0
). Let x
represent the maximum number of products given to any store. You want x
to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.Return the minimum possible x
.
Example 1:
Input: n = 6, quantities = [11,6]
Output: 3
Explanation: One optimal way is:
The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3
The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3
The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.
Example 2:
Input: n = 7, quantities = [15,10,10]
Output: 5
Explanation: One optimal way is:
The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5
The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5
The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5
The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.
Example 3:
Input: n = 1, quantities = [100000]
Output: 100000
Explanation: The only optimal way is:
The maximum number of products given to any store is max(100000) = 100000.
Constraints:
m == quantities.length
1 <= m <= n <= 105
1 <= quantities[i] <= 105
class Solution {
fun minimizedMaximum(n: Int, q: IntArray): Int {
var min = 1
var max = maxi(q)
var ans = 0
while (min <= max) {
val mid = min + (max - min) / 2
if (condition(q, mid, n)) {
ans = mid
max = mid - 1
} else {
min = mid + 1
}
}
return ans
}
private fun condition(arr: IntArray, mid: Int, n: Int): Boolean {
var ans = 0
for (num in arr) {
ans += num / mid
if (num % mid != 0) {
ans++
}
}
return ans <= n
}
private fun maxi(arr: IntArray): Int {
var ans = 0
for (n in arr) {
ans = ans.coerceAtLeast(n)
}
return ans
}
}