Make Array Zero by Subtracting Equal Amounts - Problem
You are given a non-negative integer array nums. Your goal is to make all elements equal to zero by performing a series of special operations.
In each operation, you must:
- Choose a positive integer
xwherex โค smallest non-zero elementin the array - Subtract
xfrom every positive element in the array
For example, if nums = [3, 1, 6], the smallest non-zero element is 1. You could choose x = 1 and subtract it from all positive elements: [3-1, 1-1, 6-1] = [2, 0, 5].
Return the minimum number of operations needed to make every element in nums equal to 0.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1, 5, 0, 3, 5]
โบ
Output:
3
๐ก Note:
The unique non-zero values are {1, 5, 3}. Operation 1: subtract 1 โ [0,4,0,2,4]. Operation 2: subtract 2 โ [0,2,0,0,2]. Operation 3: subtract 2 โ [0,0,0,0,0].
example_2.py โ All Zeros
$
Input:
nums = [0]
โบ
Output:
0
๐ก Note:
The array already contains only zeros, so no operations are needed.
example_3.py โ All Same Values
$
Input:
nums = [3, 3, 3, 3]
โบ
Output:
1
๐ก Note:
All non-zero elements have the same value (3), so only one operation is needed to make all elements zero.
Constraints
- 1 โค nums.length โค 100
- 0 โค nums[i] โค 100
- Follow up: Can you solve this in O(n) time?
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Containers have water levels [3, 1, 6]. Lowest non-empty = 1
2
First Drain
Drain 1 unit from all โ [2, 0, 5]. Container 2 is now empty
3
Second Drain
Drain 2 units from remaining โ [0, 0, 3]. Container 1 is now empty
4
Final Drain
Drain 3 units from last container โ [0, 0, 0]. All empty!
Key Takeaway
๐ฏ Key Insight: The number of operations equals the number of unique non-zero water levels, since each unique level requires exactly one draining operation to eliminate.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code