#2289
Steps to Make Array Non-decreasing
MediumArrayLinked ListDynamic ProgrammingStackMonotonic StackSimulationStackDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal solution, we recognize that each element can be removed based on how many steps it takes for it to be removed. We can use a stack to track the maximum number of steps required for each element efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a dp array to track the number of steps for each element.
- 2Step 2: Use a stack to keep track of indices of elements in a non-decreasing manner.
- 3Step 3: For each element, check the stack to determine how many steps it will take to remove it.
- 4Step 4: Update the dp array and the maximum steps accordingly.
solution.py14 lines
1# Full working Python code
2
3def steps_to_make_non_decreasing(nums):
4 n = len(nums)
5 dp = [0] * n
6 stack = []
7 for i in range(n):
8 while stack and nums[stack[-1]] > nums[i]:
9 dp[i] = max(dp[i], dp[stack.pop()] + 1)
10 stack.append(i)
11 return max(dp)
12
13# Example usage
14print(steps_to_make_non_decreasing([5,3,4,4,7,3,6,11,8,5,11]))ℹ
Complexity note: The time complexity is O(n) because we traverse the array once, and each element is pushed and popped from the stack at most once. The space complexity is O(n) due to the dp array and stack.
- 1An element is removed if there is a greater element to its left.
- 2The number of steps for an element depends on the maximum steps of elements that precede it.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.