-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
41 lines (35 loc) · 1009 Bytes
/
Copy pathsolution.cpp
File metadata and controls
41 lines (35 loc) · 1009 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
39
40
41
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int longestSubarray(vector<int>& arr) {
int n = arr.size();
vector<int> left(n), right(n);
stack<int> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && arr[st.top()] <= arr[i]) {
st.pop();
}
left[i] = st.empty() ? -1 : st.top();
st.push(i);
}
while (!st.empty()) st.pop();
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && arr[st.top()] <= arr[i]) {
st.pop();
}
right[i] = st.empty() ? n : st.top();
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 = max(ans, length);
}
}
return ans;
}
};