Problem Description
Given an integer array nums, a ramp is defined as a pair (i, j) such that i < j and nums[i] <= nums[j]. The width of the ramp is j - i. The problem asks for the maximum width ramp in the array. If no ramp exists, return 0.
Key Insights
- We need to identify pairs (i, j) where i < j and nums[i] <= nums[j].
- A monotonic decreasing stack can be constructed to maintain candidate starting indices.
- By iterating from left to right, we push indices onto the stack only when they have a smaller value than the last.
- Then, a backward pass from the end of the array allows us to efficiently match each element with the smallest possible candidate index from the stack.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution is built in two phases:
- Build a decreasing stack of indices by iterating through the array (only push an index if its value is less than the value at the current top of the stack).
- Iterate through the array backwards. For each index j, check and pop elements from the stack while nums[j] is greater than or equal to the nums value at the popped index. For each valid ramp found, compute the width (j - popped index) and update the maximum width accordingly. This approach guarantees we examine each element a constant number of times ensuring an efficient solution.