-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.py
More file actions
28 lines (23 loc) · 747 Bytes
/
Copy pathsolution.py
File metadata and controls
28 lines (23 loc) · 747 Bytes
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
class Solution:
def longestSubarray(self, arr):
n = len(arr)
left = [0] * n
right = [0] * n
st = []
for i in range(n):
while st and arr[st[-1]] <= arr[i]:
st.pop()
left[i] = st[-1] if st else -1
st.append(i)
st = []
for i in range(n-1, -1, -1):
while st and arr[st[-1]] <= arr[i]:
st.pop()
right[i] = st[-1] if st else n
st.append(i)
ans = 0
for i in range(n):
length = right[i] - left[i] - 1
if arr[i] <= length:
ans = max(ans, length)
return ans