Steps to Make Array Non-decreasing Problem
Description
LeetCode Problem 2289.
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 until nums becomes a non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Example 2:
Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Monotonic Stack from the Right
In one step every element that has a larger element directly before it is removed. Instead of simulating the steps, work out for each element how many steps pass before it is removed.
Process the array from right to left with a stack of indices. For element i, the stack holds later elements that are still waiting to be removed. While the top of the stack has a smaller value than nums[i], element i will eat it: the time for i is at least one more than the time taken so far, and at least as long as that element took to disappear. So for each popped element j, set dp[i] = max(dp[i] + 1, dp[j]). Then push i.
An element that eats nothing has dp[i] = 0, meaning it is never removed. The answer is the largest dp[i].
Complexity: O(n) time, because every index is pushed and popped at most once, and O(n) extra space.
class Solution:
def totalSteps(self, nums: List[int]) -> int:
stk = []
ans, n = 0, len(nums)
dp = [0] * n
for i in range(n - 1, -1, -1):
while stk and nums[i] > nums[stk[-1]]:
dp[i] = max(dp[i] + 1, dp[stk.pop()])
stk.append(i)
return max(dp)