Problem 590
Maximum Width Ramp
Medium · 20 pts · Array, Monotonic Stack
Problem
A ramp is a pair of indices i < j with A[i] <= A[j], and its width is j - i. Find the largest width of any ramp in the array, or 0 if there is none. Build a stack of indices whose values strictly decrease from the left (only these can be the best left end). Then scan j from the right end towards the left, and while the value at the top of the stack is at most A[j], pop it and record the width.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the maximum ramp width, or 0.
Constraints
2 <= N <= 50000; 0 <= A[i] <= 50000
Example input
6 6 0 8 2 1 5
Example output
4
Explanation
In 6 0 8 2 1 5, the pair (1, 5) has A[1] = 0 <= A[5] = 5, a ramp of width 4. No wider ramp exists, so the answer is 4.