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(i, j)ijiji < jnums[i] <= nums[j]j - i
Example 1
Output: 4
Explanation: the ramp (1, 5) has nums[1] = 0 and nums[5] = 5, and its width is 5 - 1 = 4.
Example 2
Output: 7
Explanation: the ramp (2, 9) has nums[2] = 1 and nums[9] = 1, and its width is 9 - 2 = 7.
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.
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]
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 jjnums[j]
In Example 2, jj
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 jj
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]
Java Solution
The method maxWidthRamp
- First, collect the candidate starts. Create an
namedArrayDeque , and walk a loop withstack from left to right. Pushi when the stack is empty ori is smaller than the number at the top,nums[i] .nums[stack.peek()] - Set
to 0. It holds the widest ramp found so far.best - Walk a second loop with
from the last position down to 0. Inside it, aj loop checks the top of the stack: as long aswhile , it pops that start and keepsnums[stack.peek()] <= nums[j] minus it inj if that is wider.best - When
has passed position 0, returnj .best
The main
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:
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]j
The fourth line, 2, comes from [3, 3, 3]nums[i] <= nums[j]
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
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
. Thej 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²).while - 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