#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; for (int i = 0; i < towersCount; ++i) { cin >> tmp; heights[i] = tmp; } stack myStack; CNode tmpNode{heights[0],0}; myStack.push(tmpNode); for (ll i = 0; i < towersCount - 1; i++){ if ( heights[i] > heights[i+1] && i + 1 != towersCount - 1) { CNode tmpNode2 = {heights[i+1], i+1}; myStack.push(tmpNode2); } if ( heights [i+1] == heights[i] ) { if(!myStack.empty()) myStack.top().index = i+1; else { CNode tmpNode2 = {heights[i+1], i+1}; myStack.push(tmpNode2); } } if ( heights[i] < heights [i+1] ){ while (!myStack.empty()){ CNode tmpNode3 = myStack.top(); if(tmpNode3.height < heights [i+1]) myStack.pop(); else if(tmpNode3.height == heights[i+1]) { myStack.pop(); count+=(i+1-tmpNode3.index)-1; } else { break; } } CNode tmpNode4 {heights[i], i }; myStack.push(tmpNode4); } } while (!myStack.empty()){ CNode tmpNode3 = myStack.top(); myStack.pop(); if(tmpNode3.height == heights[towersCount - 1]) { count+=(towersCount - 1-tmpNode3.index)-1; } } cout << count << endl; return 0; }