DDSA Solutions

962. Maximum Width Ramp

Time: O(n)
Space: O(n)

Problem Overview

Maximum Width Ramp (Medium) asks you to solve a structured algorithmic task. This is a common Array / Stack pattern in coding interviews. Build a decreasing-value stack of indices left-to-right; scan right-to-left popping while nums[j] >= nums[stack.top].

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Build a decreasing-value stack of indices left-to-right; scan right-to-left popping while nums[j] >= nums[stack.top].

Related patterns: Array, Stack, Monotonic Stack

962.cs
C#
// Approach: Build a decreasing-value stack of indices left-to-right; scan right-to-left popping while nums[j] >= nums[stack.top].
// Time: O(n) Space: O(n)

public class Solution
{
    public int MaxWidthRamp(int[] nums)
    {
        int ans = 0;
        Stack<int> stack = new Stack<int>();

        for (int i = 0; i < nums.Length; ++i)
        {
            if (stack.Count == 0 || nums[i] < nums[stack.Peek()])
                stack.Push(i);
        }

        for (int i = nums.Length - 1; i > ans; --i)
        {
            while (stack.Count > 0 && nums[i] >= nums[stack.Peek()])
                ans = Math.Max(ans, i - stack.Pop());
        }

        return ans;
    }
}
Was this solution helpful?

Related Problems