-
Notifications
You must be signed in to change notification settings - Fork 43
/
maximum-width-ramp.py
42 lines (40 loc) · 1 KB
/
maximum-width-ramp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/85223568
# IDEA : STACK
class Solution(object):
def maxWidthRamp(self, A):
"""
:type A: List[int]
:rtype: int
"""
N = len(A)
stack = []
res = 0
for i, a in enumerate(A):
if not stack or stack[-1][1] > a:
stack.append((i, a))
else:
x = len(stack) - 1
while x >= 0 and stack[x][1] <= a:
res = max(res, i - stack[x][0])
x -= 1
return res
# V2
# Time: O(n)
# Space: O(n)
class Solution(object):
def maxWidthRamp(self, A):
"""
:type A: List[int]
:rtype: int
"""
result = 0
s = []
for i in A:
if not s or A[s[-1]] > A[i]:
s.append(i)
for j in reversed(range(len(A))):
while s and A[s[-1]] <= A[j]:
result = max(result, j-s.pop())
return result