-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
38 lines (32 loc) · 997 Bytes
/
Copy pathsolution.java
File metadata and controls
38 lines (32 loc) · 997 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
37
38
import java.util.*;
class Solution {
public static int longestSubarray(int[] arr) {
int n = arr.length;
int[] left = new int[n];
int[] right = new int[n];
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] <= arr[i]) {
st.pop();
}
left[i] = st.isEmpty() ? -1 : st.peek();
st.push(i);
}
st.clear();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && arr[st.peek()] <= arr[i]) {
st.pop();
}
right[i] = st.isEmpty() ? n : st.peek();
st.push(i);
}
int ans = 0;
for (int i = 0; i < n; i++) {
int length = right[i] - left[i] - 1;
if (arr[i] <= length) {
ans = Math.max(ans, length);
}
}
return ans;
}
}