Minimum Operations to Make Numbers Non-positive — LeetCode 2702 Python Solution
- Problem
- #2702
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
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 lComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(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.