> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/oj-practices/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/oj-practices/chapter1/stack/962-maximum-width-ramp.md).

# 962 Maximum Width Ramp

## 962. [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/)

## 1. Question

Given an array`A`of integers, a*ramp* is a tuple`(i, j)`for which`i < j` and `A[i] <= A[j]`. The width of such a ramp is`j - i`.

Find the maximum width of a ramp in`A`. If one doesn't exist, return 0.

**Example 1:**

```
Input: 
[6,0,8,2,1,5]
Output: 4
Explanation: 
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.
```

**Example 2:**

```
Input: 
[9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: 
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
```

**Note:**

1. `2 <= A.length <= 50000`
2. `0 <= A[i] <= 50000`

## 2. Implementation

**(1) Stack**

思路: 这道题要我们对于每个数A\[j]，从左边找到一个数A\[i]小于等于A\[j]，其中i <= j, 找出(j - i)的最大差值。因为对于每个数，我们要往前找出一个小于等于它自己的数, 所以我们通过stack建立一个单调递减stack，这样stack.top()的数保证是小于等于当前的数。

* 所以第一步是扫一遍输入数组，建立单调递减stack，将符合条件的数的index放在stack中
* 第二步从后往前再扫一遍数组，如果stack.top()的数小于等于当前的数，则我们算出结果，并更新res的最大值

```java
class Solution {
    public int maxWidthRamp(int[] A) {
        Stack<Integer> stack = new Stack();

        for (int i = 0; i < A.length; i++) {
           if (stack.isEmpty() || A[stack.peek()] > A[i]) {
               stack.push(i);
           }
        }

        int res = 0;
        for (int i = A.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && A[stack.peek()] <= A[i]) {
                res = Math.max(res, i - stack.pop());
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

**Stack**: Time: O(n), Space: O(n)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/oj-practices/chapter1/stack/962-maximum-width-ramp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
