Problem
You are given an array nums
of size n
, consisting of non-negative integers. Your task is to apply some (possibly zero) operations on the array so that all elements become 0.
In one operation, you can select a subarray [i, j]
(where 0 <= i <= j < n
) and set all occurrences of the minimum non-negative integer in that subarray to 0.
Return the minimum number of operations required to make all elements in the array 0.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= n == nums.length <= 10^5
0 <= nums[i] <= 10^5
Method 1 – Naive Disjoint Subarray Counting
Intuition
The key idea is that we can only remove the minimum value of a subarray in one operation. For each unique value greater than zero, we need to count how many disjoint subarrays are needed to cover all its occurrences. Each block of consecutive occurrences can be removed in one operation.
Approach
- For each unique value
x > 0
innums
, find all its positions. - Count the number of disjoint blocks (consecutive runs) of
x
in the array. - For each block, increment the operation count.
- Sum the counts for all unique values to get the answer.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * u)
, whereu
is the number of unique values innums
. - 🧺 Space complexity:
O(n + u)
, for storing positions and unique values.
Method 2 – Monotonic Stack for Increasing Segments
Intuition
We can think of the array in terms of increasing segments. For every value that is greater than the last seen (and not already part of a valid subarray), we need a new operation. A monotonic stack helps track where a new operation is needed by maintaining the current segment.
Approach
- Initialize an empty stack and a counter for operations.
- Iterate through
nums
:- While the stack is not empty and the current number is less than the top, pop from the stack.
- If the stack is empty or the current number is greater than the top, increment the operation count (if the number is greater than zero) and push the number onto the stack.
- Return the total operation count.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, each element is pushed and popped at most once. - 🧺 Space complexity:
O(n)
, stack space in worst case.