#962
Maximum Width Ramp
MediumArrayTwo PointersStackMonotonic StackMonotonic StackTwo Pointers
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)
We can use a monotonic stack to keep track of indices of the array in increasing order. This allows us to efficiently find the maximum width by leveraging the properties of the ramp.
⚙️
Algorithm
3 steps- 1Step 1: Create an empty stack to hold indices.
- 2Step 2: Iterate through the array and push indices onto the stack where the values are in increasing order.
- 3Step 3: Iterate through the array in reverse to find the maximum width by popping from the stack when we find a valid ramp condition.
solution.py11 lines
1def maxWidthRamp(nums):
2 stack = []
3 n = len(nums)
4 for i in range(n):
5 if not stack or nums[stack[-1]] > nums[i]:
6 stack.append(i)
7 max_width = 0
8 for j in range(n - 1, -1, -1):
9 while stack and nums[stack[-1]] <= nums[j]:
10 max_width = max(max_width, j - stack.pop())
11 return max_widthℹ
Complexity note: The time complexity is O(n) because we traverse the array a constant number of times. The space complexity is O(n) due to the stack storing indices.
- 1Using a stack can help efficiently manage indices and find valid pairs.
- 2Understanding the properties of the ramp allows for optimized searching.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.