#2064
Minimized Maximum of Products Distributed to Any Store
MediumArrayBinary SearchGreedyBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * m) | O(n log m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log m)Space O(1)
The optimal approach uses binary search to efficiently find the minimum possible maximum number of products per store. This leverages the monotonic nature of the problem, where if a certain x is valid, all larger x are also valid.
⚙️
Algorithm
4 steps- 1Step 1: Set low to 1 and high to the maximum quantity in the quantities array.
- 2Step 2: Perform binary search: while low is less than or equal to high, calculate mid as the average of low and high.
- 3Step 3: Check if mid is a valid maximum by calculating how many stores can be filled with mid products each. If valid, move high to mid - 1; otherwise, move low to mid + 1.
- 4Step 4: The lowest valid mid found will be the answer.
solution.py14 lines
1def minimizedMaximum(n, quantities):
2 def canDistribute(x):
3 stores_filled = 0
4 for quantity in quantities:
5 stores_filled += quantity // x
6 return stores_filled >= n
7 low, high = 1, max(quantities)
8 while low <= high:
9 mid = (low + high) // 2
10 if canDistribute(mid):
11 high = mid - 1
12 else:
13 low = mid + 1
14 return lowℹ
Complexity note: This complexity arises because we perform a binary search (log m) on the maximum quantity and for each mid, we check distribution (O(n)).
- 1The problem has a monotonic property: if a certain maximum x is valid, any larger x is also valid.
- 2Binary search is a powerful technique for optimization problems where you need to minimize or maximize a value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.