本題題意:
在數組中,找到最大的j-i,使得i<j and A[i] <= A[j]java
思路:
維持一個遞減的棧,遇到比棧頂小的元素,進棧;
比大於等於棧頂的元素-> 找到棧中第一個小於等於該元素的下標
時間: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)); } }
進一步的棧利用:code
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;