962. Maximum Width Ramp #687
Answered
by
kovatz
mah-shamim
asked this question in
Q&A
-
Topics: A ramp in an integer array Given an integer array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Answered by
kovatz
Oct 10, 2024
Replies: 1 comment 2 replies
-
We can leverage the concept of a monotonic stack. Here's the solution and explanation: Approach:
Let's implement this solution in PHP: 962. Maximum Width Ramp <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxWidthRamp($nums) {
$n = count($nums);
$stack = [];
$maxWidth = 0;
// Step 1: Create a decreasing stack
for ($i = 0; $i < $n; $i++) {
// Add index only if the current value is less than the value at the index at the top of the stack
if (empty($stack) || $nums[$stack[count($stack) - 1]] > $nums[$i]) {
array_push($stack, $i);
}
}
// Step 2: Traverse from the end of the array
for ($j = $n - 1; $j >= 0; $j--) {
// While the stack is not empty and nums[stackTop] <= nums[j]
while (!empty($stack) && $nums[$stack[count($stack) - 1]] <= $nums[$j]) {
// Calculate the ramp width and update maxWidth
$i = array_pop($stack);
$maxWidth = max($maxWidth, $j - $i);
}
}
return $maxWidth;
}
// Example 1
$nums = [6, 0, 8, 2, 1, 5];
echo maxWidthRamp($nums); // Output: 4
// Example 2
$nums = [9, 8, 1, 0, 1, 9, 4, 0, 4, 1];
echo maxWidthRamp($nums); // Output: 7
?> Explanation:
Output:
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mah-shamim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can leverage the concept of a monotonic stack. Here's the solution and explanation:
Approach:
nums[stack[i]]
is in a decreasing order. This allows us to later find pairs(i, j)
wherenums[i] <= nums[j]
.j
fromn-1
to0
) to try and find the farthesti
for eachj
wherenums[i] <= nums[j]
.nums[i] <= nums[j]
holds for the current top of the stack, calculate the ramp widthj - i
and update the maximum width if it's larger.Let's implement this solution in PHP: 962. M…