Skip to content

2064. Minimized Maximum of Products Distributed to Any Store 👍

  • Time: $O(n\log(\max(\texttt{quantities})))$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int minimizedMaximum(int n, vector<int>& quantities) {
    int l = 1;
    int r = ranges::max(quantities);

    while (l < r) {
      const int m = (l + r) / 2;
      if (numStores(quantities, m) <= n)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

 private:
  int numStores(const vector<int>& quantities, int m) {
    // ceil(q / m)
    return accumulate(
        quantities.begin(), quantities.end(), 0,
        [&](int subtotal, int q) { return subtotal + (q - 1) / m + 1; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int minimizedMaximum(int n, int[] quantities) {
    int l = 1;
    int r = Arrays.stream(quantities).max().getAsInt();

    while (l < r) {
      final int m = (l + r) / 2;
      if (numStores(quantities, m) <= n)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  private int numStores(int[] quantities, int m) {
    // ceil(q / m)
    return Arrays.stream(quantities).reduce(0, (subtotal, q) -> subtotal + (q - 1) / m + 1);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def minimizedMaximum(self, n: int, quantities: list[int]) -> int:
    l = 1
    r = max(quantities)

    def numStores(m: int) -> int:
      return sum((q - 1) // m + 1 for q in quantities)

    while l < r:
      m = (l + r) // 2
      if numStores(m) <= n:
        r = m
      else:
        l = m + 1

    return l