Minimum Operations to Make Numbers Non-positive — LeetCode 2702 Python Solution

HardLeetCode PremiumArrayBinary Search
Problem
#2702
Reading time
3 min

The problem

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.

Example

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:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2702. Minimum Operations to Make Numbers Non-positive is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2702. Minimum Operations to Make Numbers Non-positive?
LeetCode 2702. Minimum Operations to Make Numbers Non-positive is rated Hard on LeetCode.
What topics does LeetCode 2702. Minimum Operations to Make Numbers Non-positive cover?
LeetCode 2702. Minimum Operations to Make Numbers Non-positive is tagged Array and Binary Search on LeetCode.
Is LeetCode 2702. Minimum Operations to Make Numbers Non-positive a premium problem?
Yes. LeetCode 2702. Minimum Operations to Make Numbers Non-positive is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview