Skip to content

2702. Minimum Operations to Make Numbers Non-positive 👍

  • 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
27
28
29
class Solution {
 public:
  int minOperations(vector<int>& nums, int x, int y) {
    int l = 0;
    int r = ranges::max(nums);

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

    return l;
  }

 private:
  // Returns true if it's possible to make all `nums` <= 0 using m operations.
  bool isPossible(const vector<int>& nums, int x, int y, int m) {
    long additionalOps = 0;
    // If we want m operations, first decrease all the numbers by y * m. Then,
    // we have m operations to select indices to decrease them by x - y.
    for (const int num : nums)
      additionalOps +=
          max(0L, (num - static_cast<long>(y) * m + x - y - 1) / (x - y));
    return additionalOps <= m;
  }
};
 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 minOperations(int[] nums, int x, int y) {
    int l = 0;
    int r = Arrays.stream(nums).max().getAsInt();

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

    return l;
  }

  // Returns true if it's possible to make all `nums` <= 0 using m operations.
  private boolean isPossible(int[] nums, int x, int y, int m) {
    long additionalOps = 0;
    // If we want m operations, first decrease all the numbers by y * m. Then,
    // we have m operations to select indices to decrease them by x - y.
    for (final int num : nums)
      additionalOps += Math.max(0L, (num - 1L * y * m + x - y - 1) / (x - y));
    return additionalOps <= m;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minOperations(self, nums: list[int], x: int, y: int) -> int:
    def isPossible(m: int) -> bool:
      """
      Returns True if it's possible to make all `nums` <= 0 using m operations.
      """
      # If we want m operations, first decrease all the numbers by y * m. Then
      # we have m operations to select indices to decrease them by x - y.
      return sum(max(0, math.ceil((num - y * m) / (x - y)))
                 for num in nums) <= m

    return bisect.bisect_left(range(max(nums)), True,
                              key=isPossible)