#3523
Make Array Non-decreasing
MediumArrayStackGreedyMonotonic StackGreedyMonotonic Stack
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
By iterating backwards, we can track the maximum values and determine the longest non-decreasing sequence efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to track the last maximum value and the size of the resulting array.
- 2Step 2: Iterate through the array from the end to the start, updating the last maximum and counting elements that can be part of the non-decreasing sequence.
- 3Step 3: Return the size of the resulting non-decreasing array.
solution.py8 lines
1def maxNonDecreasing(nums):
2 last_max = float('inf')
3 count = 0
4 for num in reversed(nums):
5 if num <= last_max:
6 count += 1
7 last_max = num
8 return countℹ
Complexity note: This solution runs in linear time as it processes each element once, maintaining a constant space.
- 1Iterating backwards helps maintain order while counting.
- 2Replacing subarrays with their maximum can help form longer non-decreasing sequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.