Skip to content

1760. Minimum Limit of Balls in a Bag 👍

  • Time: $O(n\log(\max(\texttt{nums})))$
  • 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
26
class Solution {
 public:
  int minimumSize(vector<int>& nums, int maxOperations) {
    int l = 1;
    int r = ranges::max(nums);

    while (l < r) {
      const int m = (l + r) / 2;
      if (numOperations(nums, m) <= maxOperations)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

 private:
  // Returns the number of operations required to make m penalty.
  int numOperations(const vector<int>& nums, int m) {
    int operations = 0;
    for (const int num : nums)
      operations += (num - 1) / m;
    return operations;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int minimumSize(int[] nums, int maxOperations) {
    int l = 1;
    int r = Arrays.stream(nums).max().getAsInt();

    while (l < r) {
      final int m = (l + r) / 2;
      if (numOperations(nums, m) <= maxOperations)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  // Returns the number of operations required to make m penalty.
  private int numOperations(int[] nums, int m) {
    int operations = 0;
    for (final int num : nums)
      operations += (num - 1) / m;
    return operations;
  }
}
1
2
3
4
5
6
7
class Solution:
  def minimumSize(self, nums: list[int], maxOperations: int) -> int:
    # Returns the number of operations required to make m penalty.
    def numOperations(m: int) -> int:
      return sum((num - 1) // m for num in nums) <= maxOperations
    return bisect.bisect_left(range(1, max(nums)), True,
                              key=lambda m: numOperations(m)) + 1