[leetcode]962. Maximum Width Ramp
Analysis
raining outside…—— [每天刷题并不难0.0]
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.
Explanation:
One pass the array, push the elements into a decresing stack by tracking their indexes. Then pass the array again from right to left to find the answer.
Implement
class Solution {
public:
int maxWidthRamp(vector<int>& A) {
int len = A.size();
int res = 0;
stack<int> s;
for(int i=0; i<len; i++){
if(s.empty() || A[s.top()] >= A[i])
s.push(i);
}
for(int i=len-1; i>=0; i--){
while(!s.empty() && A[s.top()] <= A[i]){
res = max(res, i-s.top());
s.pop();
}
}
return res;
}
};