#include // clang-format off using Int = long long; #define REP_(i, a_, b_, a, b, ...) for (Int i = (a), lim##i = (b); i < lim##i; i++) #define REP(i, ...) REP_(i, __VA_ARGS__, __VA_ARGS__, 0, __VA_ARGS__) struct SetupIO { SetupIO() { std::cin.tie(nullptr), std::ios::sync_with_stdio(false), std::cout << std::fixed << std::setprecision(13); } } setup_io; #ifndef _MY_DEBUG #define dump(...) #endif // clang-format on /** * author: knshnb * created: Fri Apr 17 22:55:02 JST 2020 **/ template inline bool chmin(T& a, const T& b) { if (a <= b) return false; a = b; return true; } template inline bool chmax(T& a, const T& b) { if (a >= b) return false; a = b; return true; } const Int INF = 1e9; signed main() { Int n; std::cin >> n; std::vector a(n); REP(i, n) std::cin >> a[i]; auto dfs = [&](auto f, Int s, Int t) -> Int { if (t - s <= 1) return 0; Int mid = (s + t) / 2; Int ret = f(f, s, mid) + f(f, mid, t); REP(_, 2) { std::vector mis(t - mid + 1, INF), mas(t - mid + 1, -INF), num(t - mid + 1); Int ma = -INF; REP(i, t - mid) { mis[i + 1] = std::min(mis[i], a[mid + i]); mas[i + 1] = std::max(mas[i], a[mid + i]); num[i + 1] = num[i] + chmax(ma, a[mid + i]); } Int cur_mi = INF, cur_ma = -INF; for (Int i = mid - 1; i >= s; i--) { chmax(cur_ma, a[i]); if (!chmin(cur_mi, a[i])) continue; Int it1 = std::lower_bound(mas.begin(), mas.end(), cur_ma) - mas.begin(); Int it2 = std::lower_bound(mis.begin(), mis.end(), cur_mi, std::greater()) - mis.begin(); ret += std::max(0LL, num[it2 - 1] - num[it1 - 1]); } REP(i, s, t) a[i] = -a[i]; } return ret; }; std::cout << dfs(dfs, 0, n) << std::endl; }