Home > Article > Backend Development > . Maximum Width Ramp
962. Maximum Width Ramp
Difficulty: Medium
Topics: Array, Stack, Monotonic Stack
A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.
Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.
Example 1:
Example 2:
Constraints:
Solution:
We can leverage the concept of a monotonic stack. Here's the solution and explanation:
Let's implement this solution in PHP: 962. Maximum Width Ramp
Explanation:
Create a Decreasing Stack:
- Iterate through the array and add indices to the stack.
- Only add an index if it corresponds to a value that is less than or equal to the value of the last index in the stack. This ensures that values in the stack are in a decreasing order.
Traverse from the End:
- As we go backward through the array, for each j, pop indices i from the stack as long as nums[i] <= nums[j].
- Calculate the width j - i and update maxWidth.
Why This Works:
- By maintaining a decreasing stack of indices, we ensure that when we encounter a j with a larger value, it can give us a larger width j - i when i is popped from the stack.
Time Complexity:
- Building the stack takes O(n) time since each index is pushed once.
- The traversal from the end and popping indices also takes O(n) since each index is popped at most once.
- Overall, the solution runs in O(n) time, which is efficient for input size up to 5 * 10^4.
Output:
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Maximum Width Ramp. For more information, please follow other related articles on the PHP Chinese website!