-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
36 lines (31 loc) · 822 Bytes
/
Copy pathsolution.js
File metadata and controls
36 lines (31 loc) · 822 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
29
30
31
32
33
34
35
36
class Solution {
longestSubarray(arr) {
const n = arr.length;
const left = new Array(n);
const right = new Array(n);
let st = [];
for (let i = 0; i < n; i++) {
while (st.length > 0 && arr[st[st.length - 1]] <= arr[i]) {
st.pop();
}
left[i] = st.length === 0 ? -1 : st[st.length - 1];
st.push(i);
}
st = [];
for (let i = n - 1; i >= 0; i--) {
while (st.length > 0 && arr[st[st.length - 1]] <= arr[i]) {
st.pop();
}
right[i] = st.length === 0 ? n : st[st.length - 1];
st.push(i);
}
let ans = 0;
for (let i = 0; i < n; i++) {
const length = right[i] - left[i] - 1;
if (arr[i] <= length) {
ans = Math.max(ans, length);
}
}
return ans;
}
}