-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonotonic_stack.cpp
More file actions
36 lines (28 loc) · 1.23 KB
/
monotonic_stack.cpp
File metadata and controls
36 lines (28 loc) · 1.23 KB
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
// Monotonic Stack function to find next greater or next smaller element
vector<int> monotonicStack(const vector<int>& arr, bool findNextGreater = true) {
int n = arr.size();
vector<int> res(n, -1);
stack<int> st; // Stack to store indices
for (int i = 0; i < n; ++i) {
while (!st.empty() && (findNextGreater ? arr[st.top()] < arr[i] : arr[st.top()] > arr[i])) {
res[st.top()] = i; // Update result (index of next greater/smaller element)
st.pop();
}
st.push(i); // Push current index onto the stack
}
return res;
}
// Monotonic Stack function to find previous greater or previous smaller element
vector<int> previousMonotonicStack(const vector<int>& arr, bool findPreviousGreater = true) {
int n = arr.size();
vector<int> res(n, -1);
stack<int> st; // Stack to store indices
for (int i = 0; i < n; ++i) {
while (!st.empty() && (findPreviousGreater ? arr[st.top()] <= arr[i] : arr[st.top()] >= arr[i]))
st.pop();
if (!st.empty())
res[i] = st.top(); // Update result with the index of the previous greater/smaller element
st.push(i); // Push current index onto the stack
}
return res;
}