[LeetCode] Minimum Operations to Make Numbers Non-positive

2702. Minimum Operations to Make Numbers Non-positive

You are given a 0-indexed integer array nums and two integers x and y. In one operation, you must choose an index i such that 0 <= i < nums.length and perform the following:

  • Decrement nums[i] by x.
  • Decrement values by y at all indices except the ith one.

Return the minimum number of operations to make all the integers in nums less than or equal to zero.

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 {
long long helper(long long a, long long x, long long y, long long m) {
long long diff = a - y * m;
return (diff + x - y - 1) / (x - y);
}
bool helper(vector<int>& A, int x, int y, long long m) {
long long cnt = 0;
for(auto a : A) {
if(a <= y * m) continue;
cnt += helper(a,x,y,m);
if(m < cnt) return false;
}
return true;
}
public:
int minOperations(vector<int>& A, int x, int y) {
sort(begin(A), end(A));
long long l = 0, r = INT_MAX, res = r;
while(l <= r) {
long long m = l + (r - l) / 2;
bool ok = helper(A,x,y,m);
if(ok) {
res = min(res,m);
r = m - 1;
} else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/30/PS/LeetCode/minimum-operations-to-make-numbers-non-positive/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.