Maximum Width Ramp

Find two positions in an array, as far apart as possible, where the left number is no bigger than the right one.

You are given an array of integers nums. A ramp is a pair of positions (i, j), with i before j, where the number at i is no bigger than the number at j: i < j and nums[i] <= nums[j]. The width of the ramp is j - i. Return the largest width of any ramp in the array, or 0 if the array has no ramp.

Example 1
Input: nums = [6, 0, 8, 2, 1, 5]
Output: 4
Explanation: the ramp (1, 5) has nums[1] = 0 and nums[5] = 5, and its width is 5 - 1 = 4.
Example 2
Input: nums = [9, 8, 1, 0, 1, 9, 4, 0, 4, 1]
Output: 7
Explanation: the ramp (2, 9) has nums[2] = 1 and nums[9] = 1, and its width is 9 - 2 = 7.
Solution

The Idea

Picture six number cards in a row: 6, 0, 8, 2, 1 and 5, at positions 0 to 5. You want two cards as far apart as possible where the left card is not bigger than the right one. The 6 and the 8 work, two places apart. The 0 and the 5 work too, four places apart, and no pair does better, so the answer is 4.

The plain way is to check every pair of positions. Six cards have 15 pairs, but 50,000 cards have about 1.25 billion. So which pairs are really worth checking?

Call the left card of a pair its start, and the right card its end. Which starts are worth trying? Look at the 2 at position 3. Any card that the 2 makes a ramp with, the 0 at position 1 makes a ramp with too, because 0 is smaller than 2. Position 1 is further left, so its ramp is always wider. Position 3 can never start the widest ramp, and the same goes for every position that has a smaller or equal number somewhere before it.

So the widest ramp starts at a position whose number is smaller than everything before it. Call these positions the candidate starts. Look at the picture below.

The array 6, 0, 8, 2, 1, 5 at positions 0 to 5. Position 0 (number 6) and position 1 (number 0) are the candidate starts, each smaller than everything before it. An arc joins position 1 to position 5: the ramp (1, 5), with 0 <= 5 and width 4.

Position 0 is a candidate start, because nothing comes before it. Position 1 is one too, because 0 is smaller than 6. Every number after it is bigger than 0, so there are no more. The arc is the widest ramp: it starts at the candidate start at position 1 and ends at the 5 at position 5.

Read from left to right, the numbers of the candidate starts always get smaller: here 6, then 0. That order is the key: it lets a search try the candidate starts one after another and stop as soon as one is too big.

Solution Approach

Turning that idea into code means settling three things: how to collect the candidate starts, which end to try for each of them, and when a candidate start is finished.

Collecting the candidate starts

How do we find the candidate starts? Walk the array from left to right. A position is a candidate start when its number is smaller than the number of the last candidate start found, which is the smallest number seen so far.

The candidate starts go on a stack, a pile where the item put on last is the first one taken off, like a pile of plates. Each new candidate start has the smallest number yet, so the item on top always holds the smallest number. A stack whose items stay in sorted order like this is called a monotonic stack.

In Example 2, [9, 8, 1, 0, 1, 9, 4, 0, 4, 1], the candidate starts are positions 0, 1, 2 and 3, with the numbers 9, 8, 1 and 0. Position 3, with 0, ends up on top.

Trying ends from the right

Which end should each candidate start get? The one furthest to the right whose number is at least as big. So a position j walks from the last position toward the first. At each j, look at the candidate start on top of the stack. If its number is no bigger than nums[j], the two make a ramp, and its width may be the answer.

In Example 2, j starts at position 9, with the number 1. The top of the stack is position 3, with 0, so (3, 9) is a ramp of width 6. Below it is position 2, with 1, and (2, 9) is a ramp of width 7. Next comes position 1, with 8, which is bigger than 1, so this j is done.

Positions 8, 7 and 6 hold 4, 0 and 4, all smaller than the 8 now on top. At position 5, the 9 makes the ramps (1, 5), width 4, and (0, 5), width 5. The widest of them all is 7.

When a candidate start is finished

Why could position 3 come off the stack once it made a ramp with position 9? From here j only moves left, so any later end for position 3 is closer and gives a narrower ramp. Its first ramp is already its widest, so it is taken off the stack for good. That uncovers the next candidate start, which may fit the same j, as position 2 did.

Why can the check stop at the first candidate start that is too big? Everything below it on the stack has an even bigger number, so none of those fit nums[j] either. This is where the shrinking order of the candidate starts pays off.

Java Solution

The method maxWidthRamp works in these steps:

  1. First, collect the candidate starts. Create an ArrayDeque named stack, and walk a loop with i from left to right. Push i when the stack is empty or nums[i] is smaller than the number at the top, nums[stack.peek()].
  2. Set best to 0. It holds the widest ramp found so far.
  3. Walk a second loop with j from the last position down to 0. Inside it, a while loop checks the top of the stack: as long as nums[stack.peek()] <= nums[j], it pops that start and keeps j minus it in best if that is wider.
  4. When j has passed position 0, return best.

The main method runs both examples, an array that only goes down, an array of equal numbers, and an array with one number.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class MaximumWidthRamp {

    public static int maxWidthRamp(int[] nums) {
        Deque<Integer> stack = new ArrayDeque<>();   // candidate starts, smallest value on top
        for (int i = 0; i < nums.length; i++) {
            if (stack.isEmpty() || nums[i] < nums[stack.peek()]) {
                stack.push(i);                // smaller than everything before it
            }
        }
        int best = 0;
        for (int j = nums.length - 1; j >= 0; j--) {      // try ends from the right
            while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) {
                best = Math.max(best, j - stack.pop());   // no end further left can do better
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxWidthRamp(new int[] {6, 0, 8, 2, 1, 5}));
        System.out.println(maxWidthRamp(new int[] {9, 8, 1, 0, 1, 9, 4, 0, 4, 1}));
        System.out.println(maxWidthRamp(new int[] {5, 4, 3, 2, 1}));
        System.out.println(maxWidthRamp(new int[] {3, 3, 3}));
        System.out.println(maxWidthRamp(new int[] {7}));
    }
}

Running it prints:

Output
4
7
0
2
0

The first two lines are the examples, 4 and 7. The third line is 0. In [5, 4, 3, 2, 1] every number is smaller than everything before it, so every position is a candidate start, but no later number is big enough for any of them. Each start only pairs with itself, when j reaches it, and that gives width 0.

The fourth line, 2, comes from [3, 3, 3]. A ramp needs only nums[i] <= nums[j], so equal numbers count, and the first and last 3 are two places apart. The last line is 0, because a single number has no pair.

Why does the first loop push only the new smallest numbers, and not every position? With every position pushed, the stack loses its order. In Example 1, the 8 at position 2 then sits above the 0 at position 1. At j = 5, the 8 is too big for 5, so the check stops before it reaches the 0. That version returns 2 for Example 1 instead of 4, and 5 for Example 2 instead of 7.

Complexity

The method makes two passes over the array, and each position goes onto the stack and comes off it at most once.

  • Time: O(n), where n is the length of the array. The first loop takes n steps, and the second loop tries n values of j. The while loop pops a start every time it runs, and at most n were pushed, so all its runs together take at most n steps. Checking every pair would take O(n²).
  • Space: O(n). In an array that only goes down, every position is a candidate start, so the stack can hold all n positions.

Another way sorts the positions by their numbers and walks them in that order, keeping the smallest position seen so far as the best start for each one, in O(n log n) time. For another problem solved with a monotonic stack, see Sum of Subarray Minimums.