962. Maximum Width Ramp
本题题意:
在数组中,找到最大的j-i,使得i<j and A[i] <= A[j]
思路:
维持一个递减的栈,遇到比栈顶小的元素,进栈;
比大于等于栈顶的元素-> 找到栈中第一个小于等于该元素的下标
时间:O(Nlgn),空间:O(N)
List<Integer> s = new ArrayList<>();
int res = 0;
for (int i = 0; i < A.length; i++){
if (s.isEmpty() || A[ s.get(s.size() - 1) ] > A[i]){
s.add(i);
}else{
int left = 0, right = s.size() - 1;
int mid = 0;
while (left < right){
mid = (left + right) / 2;
if (A[s.get(mid)] > A[i]){
left = mid + 1;
}else{
right = mid;
}
}
res = Math.max(res, i - s.get(left));
}
}
进一步的栈利用:
Stack<Integer> s = new Stack<>();
int res = 0;
for (int i = 0; i < A.length;i++){
if (s.isEmpty() || A[s.peek()] > A[i]){
s.add(i);
}
}
for (int i = A.length - 1; i > res; i--){
while (!s.isEmpty() && A[s.peek()] <= A[i]){
res = Math.max(res, i - s.pop());
}
}
return res;