Algorithm
Problem Name: 962. Maximum Width Ramp
Problem Link: https://leetcode.com/problems/maximum-width-ramp/
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:
Input: nums = [6,0,8,2,1,5] Output: 4 Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
Example 2:
Input: nums = [9,8,1,0,1,9,4,0,4,1] Output: 7 Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.
Constraints:
2 <= nums.length <= 5 * 104
0 <= nums[i] <= 5 * 104
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int maxWidthRamp(int[] A) {
Stack stack = new Stack<>();
int ans = 0;
int n = A.length;
for (int i=0; i < n; i++) {
if (stack.isEmpty() || A[stack.peek()] > A[i]) {
stack.add(i);
}
}
for (int i=n-1; i>=ans; i--) {
while (!stack.isEmpty() && A[stack.peek()] < = A[i]) {
ans = Math.max(ans, i - stack.pop());
}
}
return ans;
}
}
Copy The Code &
Try With Live Editor
Input
nums = [6,0,8,2,1,5]
Output
4
#2 Code Example with Python Programming
Code -
Python Programming
class Solution:
def maxWidthRamp(self, A):
"""
:type A: List[int]
:rtype: int
"""
ind, mx, index = float("inf"), 0, collections.defaultdict(list)
for i, num in enumerate(A):
index[num].append(i)
A.sort()
for i in range(len(A)):
mx = max(mx, index[A[i]][-1] - ind)
ind = min(ind, index[A[i]][0])
return mx
Copy The Code &
Try With Live Editor
Input
nums = [6,0,8,2,1,5]
Output
4