Data Structures & AlgorithmsHardGoldman Sachs OA · LeetCode medium-hard

Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left ends.

Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left ends.
def ramp(a):
    st = []
    for i, x in enumerate(a):
        if not st or a[st[-1]] > x: st.append(i)
    best = 0
    for j in range(len(a) - 1, -1, -1):
        while st and a[st[-1]] <= a[j]:
            best = max(best, j - st.pop())
    return best
print(ramp([5, 2, 7, 1, 3, 4, 2, 6]))
What is printed?
  1. A. 6
  2. B. 4
  3. C. 5
  4. D. 7

Correct answer: D. 7

Only prefix minima (5, 2, 1 at indices 0, 1, 3) can be optimal left ends. Scanning from the right, a[7] = 6 pops 1, 2 and 5 in turn, and the last pop gives 7 − 0 = 7: the first and last elements already form a ramp. Pairing with the global minimum only gives width 4.

More Coding Interview Problems questions

Exams that ask this topic