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.
Example 1:
Input: [6,0,8,2,1,5]
Output: 4
Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.
Example 2:
Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
Note:
2 <= A.length <= 50000
0 <= A[i] <= 50000
Solution: Stack
- Using a stack to store start candidates’ (decreasing order) index
- Scan from right to left, compare the current number with the one on the top of the stack, pop if greater.
e.g.
A = [6,0,8,2,1,5]
stack = [0, 1] => [6, 0]
cur: A[5] = 5, stack.top = A[1] = 0, ramp = 5, stack.pop()
cur: A[4] = 1, stack.top = A[0] = 6
cur: A[3] = 2, stack.top = A[0] = 6
cur: A[2] = 8, stack.top = A[0] = 6, ramp = 2, stack.pop()
stack.isEmpty() => END
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua, running time: 44 ms class Solution { public: int maxWidthRamp(vector<int>& A) { stack<int> s; for (int i = 0; i < A.size(); ++i) if (s.empty() || A[i] < A[s.top()]) s.push(i); int ans = 0; for (int i = A.size() - 1; i >= 0; --i) while (!s.empty() && A[i] >= A[s.top()]) { ans = max(ans, i - s.top()); s.pop(); } return ans; } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 |
# Author: Huahua, running time: 92 ms class Solution: def maxWidthRamp(self, A): s = [] for i in range(len(A)): if not s or A[i] < A[s[-1]]: s.append(i) ans = 0 for i in range(len(A) - 1, -1, -1): while s and A[i] >= A[s[-1]]: ans = max(ans, i - s.pop()) return ans |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment