#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int countMaxSubarrays(const vector<int>& heights) {
int n = heights.size();
vector<int> count(n, 1); // Initializing count for each element as 1
stack<int> st; // Stack to keep track of indices
// Forward pass to calculate count for each element
for (int i = 0; i < n; ++i) {
// Pop elements from the stack while the current height is greater than or equal to the height at the top of the stack
while (!st.empty() && heights[i] >= heights[st.top()]) {
count[i] += count[st.top()]; // Add count of popped element to current element's count
st.pop();
}
st.push(i); // Push current index onto the stack
}
while (!st.empty()) {
st.pop();
}
// Backward pass to calculate count for each element
for (int i = n - 1; i >= 0; --i) {
// Pop elements from the stack while the current height is greater than the height at the top of the stack
while (!st.empty() && heights[i] > heights[st.top()]) {
count[i] += count[st.top()]; // Add count of popped element to current element's count
st.pop();
}
st.push(i); // Push current index onto the stack
}
int totalCount = 0;
for (int c : count) {
totalCount += c; // Sum up the count for each element
}
return totalCount;
}
int main() {
vector<int> heights = {1,2,1};
cout << "Count of subarrays with maximum element in each subarray: " << countMaxSubarrays(heights) << endl;
return 0;
}