Minimum Operations to Make Numbers Non-positive Problem
Description
LeetCode Problem 2702.
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]byx. - Decrement values by
yat all indices except thei^thone.
Return the minimum number of operations to make all the integers in nums less than or equal to zero.
Example 1:
Input: nums = [3,4,1,7,6], x = 4, y = 2
Output: 3
Explanation: You will need three operations. One of the optimal sequence of operations is:
Operation 1: Choose i = 3. Then, nums = [1,2,-1,3,4].
Operation 2: Choose i = 3. Then, nums = [-1,0,-3,-1,2].
Operation 3: Choose i = 4. Then, nums = [-3,-2,-5,-3,-2].
Now, all the numbers in nums are non-positive. Therefore, we return 3.
Example 2:
Input: nums = [1,2,1], x = 2, y = 1
Output: 1
Explanation: We can perform the operation once on i = 1. Then, nums becomes [0,0,0]. All the positive numbers are removed, and therefore, we return 1.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= y < x <= 10^9
Solution
Approach: Binary Search on the Answer
If t operations are enough, any larger count is enough too, so we can binary search t between 0 and max(nums).
To check a given t: every number loses t * y from the y part of all t operations. A number v still positive afterwards needs extra hits, each of which adds x - y more, so it needs ceil((v - t * y) / (x - y)) of them. The count is feasible when these extra hits total at most t.
Complexity: O(n log M) time and O(1) space, where M is the largest number.
from math import ceil
class Solution:
def minOperations(self, nums: List[int], x: int, y: int) -> int:
def check(t: int) -> bool:
cnt = 0
for v in nums:
if v > t * y:
cnt += ceil((v - t * y) / (x - y))
return cnt <= t
l, r = 0, max(nums)
while l < r:
mid = (l + r) >> 1
if check(mid):
r = mid
else:
l = mid + 1
return l