Skip to content

962. Maximum Width Ramp #687

Answered by kovatz
mah-shamim asked this question in Q&A
Oct 10, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We can leverage the concept of a monotonic stack. Here's the solution and explanation:

Approach:

  1. Monotonic Decreasing Stack: We create a stack that keeps track of indices of elements in a way such that nums[stack[i]] is in a decreasing order. This allows us to later find pairs (i, j) where nums[i] <= nums[j].
  2. Traverse from the End: After creating the stack, we traverse the array from the end (j from n-1 to 0) to try and find the farthest i for each j where nums[i] <= nums[j].
  3. Update the Maximum Width: Whenever nums[i] <= nums[j] holds for the current top of the stack, calculate the ramp width j - i and update the maximum width if it's larger.

Let's implement this solution in PHP: 962. M…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Oct 10, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 10, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants