Problem
You are given a 0-indexed integer array nums
. In one step, remove all elements nums[i]
where nums[i - 1] > nums[i]
for all 0 < i < nums.length
.
Return the number of steps performed untilnums
becomes anon-decreasing array.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
Solution
Method 1 – Reverse Monotonic Stack
Intuition
Let’s build the solution from scratch by walking through examples:
Consider nums = [10, 4, 5, 6]
.
- Going left to right, 10 > 4, so 4 is removed in round 1.
- 10 > 5, so 5 is removed in round 2.
- 10 > 6, so 6 is removed in round 3.
But this doesn’t always work for all cases. For example, nums = [10, 4, 5, 6, 3, 4]
:
- If we go left to right, we might overcount rounds. Instead, we need to process from right to left.
- When we reach 6, it removes both 3 and 4 in 2 rounds.
- When we reach 10, it removes 6 (which already removed 3 and 4 in 2 rounds), so the total rounds for 10 should be 2, not 1. When 10 removes 8, we do round + 1, i.e., 2+1 = 3.
This shows that for each element, the number of rounds is determined by the maximum rounds among the elements it removes, plus one. We use a stack to track this efficiently.
Approach
- Start from the rightmost element and move left.
- Use a stack to store pairs
(value, rounds)
. - For each element:
- Pop all elements from the stack that are smaller, updating the rounds as
max(cnt+1, popped_rounds)
. - Update the result with the maximum rounds seen so far.
- Push the current element and its rounds onto the stack.
- Pop all elements from the stack that are smaller, updating the rounds as
- Return the result.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, each element is pushed and popped at most once. - 🧺 Space complexity:
O(n)
, for the stack.