Minimum Operations to Make Numbers Non-positive - 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
  • Decrement values by y at all indices except the i-th one

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,1], x = 3, y = 1
Output: 2
💡 Note: Operation 1: Choose i=0, nums becomes [0,3,0]. Operation 2: Choose i=1, nums becomes [-1,0,-1]. All numbers ≤ 0 after 2 operations.
Example 2 — Equal x and y
$ Input: nums = [1,2,1], x = 2, y = 2
Output: 1
💡 Note: Since x = y = 2, each operation decreases all numbers by 2. After 1 operation: nums becomes [-1,0,-1]. All numbers ≤ 0.
Example 3 — Large Difference
$ Input: nums = [10], x = 5, y = 1
Output: 2
💡 Note: Only one element. Operation 1: nums[0] becomes 5. Operation 2: nums[0] becomes 0. Need 2 operations to make 10 ≤ 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ x, y ≤ 109

Visualization

Tap to expand
Minimum Operations to Make Numbers Non-positive INPUT nums array: 3 i=0 4 i=1 1 i=2 Parameters: x = 3 (target decrement) y = 1 (others decrement) Goal: Make all nums[i] <= 0 Each op: pick i, subtract x from nums[i], y from rest ALGORITHM (Greedy) 1 Op 1: Target i=1 [3,4,1] - x at i=1, y at rest [3-1, 4-3, 1-1] = [2,1,0] 2 Op 2: Target i=0 [2,1,0] - x at i=0, y at rest [2-3, 1-1, 0-1] = [-1,0,-1] 3 Op 3: Target i=1 [-1,0,-1] - x at i=1, y rest [-2,-3,-2] all <= 0! 4 Greedy Strategy Always target the max element for x reduction Optimization: Binary search on answer Check if k ops sufficient via greedy simulation FINAL RESULT Final array state: -2 -3 -2 All values <= 0 [OK] OUTPUT 3 Verification: Op 1: [3,4,1]-->[2,1,0] Op 2: [2,1,0]-->[-1,0,-1] Op 3: [-1,0,-1]-->[-2,-3,-2] 3 operations total Key Insight: The greedy approach targets the maximum element each operation for x-reduction. Binary search optimizes: for k operations, each element receives k*y reduction plus some x-reductions. We need sum of extra x-reductions <= k. Time: O(n log(max_val * n)). TutorialsPoint - Minimum Operations to Make Numbers Non-positive | Greedy Approach
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen