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 = *max_element(begin(quantities), end(quantities));

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

    return l;
  }

 private:
  int numOfStores(const vector<int>& quantities, int m) {
    // ceil(q / k)
    return accumulate(
        begin(quantities), end(quantities), 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 (numOfStores(quantities, m) <= n)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  private int numOfStores(int[] quantities, int m) {
    // Math.ceil(q / k)
    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 numOfStores(m: int) -> int:
      return sum((q - 1) // m + 1 for q in quantities)

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

    return l
Back to top