#include #ifndef LOCAL #define cerr dolor_sit_amet #endif #define mp make_pair #define sz(x) ((int)((x).size())) #define X first #define Y second #define ALL(x) (x).begin(), (x).end() using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair < int , int > ipair; typedef pair < ll , ll > lpair; const int IINF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3fll; const double DINF = numeric_limits::infinity(); const int MOD = 1000000007; const double EPS = 1e-9; const double PI = acos(-1.0); const int DX[] = { 1, 0, -1, 0, 1, -1, 1, -1}; const int DY[] = { 0, 1, 0, -1, 1, -1, -1, 1}; ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } ll sqr(ll x) { return x*x; } ll sqr(int x) { return (ll)x*x; } double sqr(double x) { return x*x; } ld sqr(ld x) { return x*x; } mt19937 mmtw(960172); ll rnd(ll x, ll y) { static uniform_int_distribution d; return d(mmtw) % (y - x + 1) + x; } // ========================================================================= // const int N = 200179; const int M = 1000179; int n; int a[N]; vector ppos[M]; int ans = 0; int cans = 0; set ones; void add(int &x, int y) { x += y; if (x >= MOD) x -= MOD; } void sub(int &x, int y) { x -= y; if (x < 0) x += MOD; } int getZC(int x) { ll r = 1LL*x*(x+1)*(2*x+1) / 6 + 1LL*x*(x+1) / 2; return (r / 2) % MOD; } int getAB(int a, int b) { --a; if (a > b) swap(a, b); if (a <= 0) return 0; int c = b - a; ll r = 1LL * c * a * (a+1) / 2; r %= MOD; r += a*(a+1LL)*(2*a+1) / 6; r %= MOD; return r; } bool was = false; int la, lb; void set1(int x) { ones.insert(x); auto it = ones.find(x); --it; int l1 = x - *it; ++it; ++it; int l2 = *it - x; if (was) { add(cans, getZC(l1 + l2 - 1)); } else { ll l = 1LL * n * (n + 1) / 2; l %= MOD; l = l * (l + 1) / 2; l %= MOD; add(cans, l); } sub(cans, getZC(l1 - 1)); sub(cans, getZC(l2 - 1)); if (was) { add(cans, getAB(la, lb)); } la = min(la, x); lb = min(lb, n - 1 - x); sub(cans, getAB(la, lb)); was = true; } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", a + i); ppos[a[i]].push_back(i); } ones.insert(-1); ones.insert(n); la = lb = n; for (int i = M - 1; i >= 1; --i) { for (int x : ppos[i]) set1(x); ans = (ans + cans) % MOD; } cout << ans << "\n"; return 0; }