#include "bits/stdc++.h" typedef long long int ll; using namespace std; ll heights [1000010]; struct CNode { ll height; ll index; }; int main() { ll towersCount = 0; cin >> towersCount; ll tmp = 0; ll count = 0; if(towersCount == 1) { cout << 0 << endl; return 0; } for (int i = 0; i < towersCount; ++i) { cin >> tmp; heights[i] = tmp; } stack myStack; myStack.push(CNode{heights[0], 0}); for (ll i = 1; i < towersCount; ++i) { if(heights[i] < heights[i-1]) { myStack.push(CNode{heights[i], i}); } if(heights[i] == heights[i-1]) { myStack.top().index = i; } if (heights[i] > heights[i-1]) { while(!myStack.empty() && myStack.top().height <= heights[i]) { if(myStack.top().height == heights[i]) { count+=i-myStack.top().index - 1; } myStack.pop(); } myStack.push(CNode{heights[i], i}); } } cout << count << endl; return 0; }