962. Maximum Width Ramp
MediumView on LeetCode
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
- 321. Create Maximum Number(Unknown)
- 769. Max Chunks To Make Sorted(Medium)
- 1475. Final Prices With a Special Discount in a Shop(Easy)
- 1526. Minimum Number of Increments on Subarrays to Form a Target Array(Unknown)
- 1574. Shortest Subarray to be Removed to Make Array Sorted(Unknown)
- 2818. Apply Operations to Maximize Score(Unknown)