#include using namespace std; int main() { int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) { cin >> a.at(i); } priority_queue q; priority_queue, greater> r; map removed_q, removed_r; int bound = 0; int64_t ans = 0; for (int i = 0; i < n; i++) { while (bound < n and bound - i < 2) { q.push(a.at(bound)); r.push(a.at(bound)); bound++; } while (bound <= n) { while (removed_q[q.top()]) { removed_q[q.top()]--; q.pop(); } int mmax = q.top(); while (removed_r[r.top()]) { removed_r[r.top()]--; r.pop(); } int m0 = r.top(); r.pop(); while (removed_r[r.top()]) { removed_r[r.top()]--; r.pop(); } int m1 = r.top(); r.push(m0); if (mmax > m0 + m1) { break; } if (bound < n) { q.push(a.at(bound)); r.push(a.at(bound)); } bound++; } removed_q[a.at(i)]++; removed_r[a.at(i)]++; ans += max(0, bound - i - 2); } cout << ans << endl; return 0; }