#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5, mo = 1e9 + 7;
int n, a[N], ct[N], iv[N], pr[N], ipr[N], prx[N];
int ans, s;
struct nod {
  int mx, cs, su, mi, cs2, su2, ct;
} t[N * 4], an;
int ksm(int x, int y) {
  int t = 1;
  for (; y; y >>= 1, x = (long long)x * x % mo)
    if (y & 1) t = (long long)t * x % mo;
  return t;
}
void ch(int v, int l, int r, int x) {
  if (prx[x] > t[v].mx) t[v].mx = prx[x], t[v].cs = t[v].su = 0;
  if (prx[x] == t[v].mx) t[v].cs++, t[v].su = (t[v].su + ipr[x]) % mo;
  if (prx[x] < t[v].mi) t[v].mi = prx[x], t[v].cs2 = t[v].su2 = 0;
  if (prx[x] == t[v].mi) t[v].cs2++, t[v].su2 = (t[v].su2 + pr[x]) % mo;
  ++t[v].ct;
  if (l == r) return;
  int m = l + r >> 1;
  if (x <= m)
    ch(v * 2, l, m, x);
  else
    ch(v * 2 + 1, m + 1, r, x);
}
void qu(int v, int l, int r, int x) {
  if (r <= x) {
    if (t[v].mx > an.mx) an.mx = t[v].mx, an.cs = 0;
    if (t[v].mx == an.mx) an.cs += t[v].cs, an.su = (an.su + t[v].su) % mo;
    return;
  }
  int m = l + r >> 1;
  if (x <= m) {
    if (t[v * 2 + 1].mi < an.mi) an.mi = t[v * 2 + 1].mi, an.cs2 = 0;
    if (t[v * 2 + 1].mi == an.mi)
      an.cs2 += t[v * 2 + 1].cs2, an.su2 = (an.su2 + t[v * 2 + 1].su2) % mo;
    an.ct += t[v * 2 + 1].ct;
    qu(v * 2, l, m, x);
  } else {
    if (t[v * 2].mx > an.mx) an.mx = t[v * 2].mx, an.cs = 0;
    if (t[v * 2].mx == an.mx)
      an.cs += t[v * 2].cs, an.su = (an.su + t[v * 2].su) % mo;
    qu(v * 2 + 1, m + 1, r, x);
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 1, _e = n; i <= _e; ++i) cin >> a[i], ++ct[a[i]];
  for (int i = n - 1, _e = 1; i >= _e; --i) ct[i] += ct[i + 1] - 1;
  for (int i = 1, _e = n; i <= _e; ++i)
    if (ct[i] <= 0) return puts("0"), 0;
  iv[1] = 1;
  for (int i = 2, _e = n; i <= _e; ++i)
    iv[i] = mo - (long long)iv[mo % i] * (mo / i) % mo;
  s = 1;
  pr[0] = 1;
  for (int i = 1, _e = n; i <= _e; ++i) {
    s = (long long)s * ct[i] % mo;
    prx[i] = prx[i - 1];
    pr[i] = pr[i - 1];
    if (ct[i] == 1)
      ++prx[i];
    else
      pr[i] = (long long)pr[i] * (ct[i] - 1) % mo * iv[ct[i]] % mo;
    ipr[i] = ksm(pr[i], mo - 2);
  }
  for (int i = 1, _e = n * 4; i <= _e; ++i) t[i].mi = N, t[i].mx = -1;
  for (int i = 1, _e = n; i <= _e; ++i) {
    an.cs = an.cs2 = an.ct = an.su = an.su2 = 0;
    an.mx = -1;
    an.mi = N;
    int y = a[i];
    qu(1, 1, n, y);
    if (an.mx == prx[y])
      ans = ((long long)an.su * pr[y] % mo * iv[2] % mo * s + ans) % mo;
    if (an.mi == prx[y])
      ans = (-(long long)an.su2 * ipr[y] % mo * iv[2] % mo * s + ans) % mo,
      ans = ((long long)an.cs2 * s + ans) % mo;
    ch(1, 1, n, y);
  }
  cout << (ans + mo) % mo;
}
