#include <bits/stdc++.h>
using namespace std;
const int N = 4e5 + 10;
const int mod = 1e9 + 7;
const int inv2 = 5e8 + 4;
int gi() {
  int x = 0, o = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') o = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return x * o;
}
int n, a[N], cnt[N];
vector<int> V[N];
int qpow(int a, int b) {
  int ret = 1;
  while (b) {
    if (b & 1) ret = 1ll * ret * a % mod;
    a = 1ll * a * a % mod;
    b >>= 1;
  }
  return ret;
}
pair<int, int> operator+(pair<int, int> a, pair<int, int> b) {
  return make_pair((a.first + b.first) % mod, a.second + b.second);
}
int tag[N << 2];
pair<int, int> tr[N << 2];
void build(int o, int l, int r) {
  tag[o] = 1;
  if (l == r) return;
  int mid = (l + r) >> 1;
  build((o << 1), l, mid);
  build((o << 1 | 1), mid + 1, r);
}
void modify(int o, int v) {
  tr[o].first = 1ll * tr[o].first * v % mod;
  tag[o] = 1ll * tag[o] * v % mod;
}
void down(int o) {
  if (tag[o] == 1) return;
  modify((o << 1), tag[o]);
  modify((o << 1 | 1), tag[o]);
  tag[o] = 1;
}
void update(int o, int l, int r, int p, int v) {
  if (l == r) {
    tr[o] = make_pair(v, 1);
    return;
  }
  down(o);
  int mid = (l + r) >> 1;
  if (p <= mid)
    update((o << 1), l, mid, p, v);
  else
    update((o << 1 | 1), mid + 1, r, p, v);
  tr[o] = tr[(o << 1)] + tr[(o << 1 | 1)];
}
pair<int, int> query(int o, int l, int r, int L, int R) {
  if (L <= l && r <= R) return tr[o];
  down(o);
  int mid = (l + r) >> 1;
  pair<int, int> ret = make_pair(0, 0);
  if (L <= mid) ret = ret + query((o << 1), l, mid, L, R);
  if (R > mid) ret = ret + query((o << 1 | 1), mid + 1, r, L, R);
  return ret;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) a[i] = gi(), cnt[a[i]]++, V[a[i]].push_back(i);
  for (int i = n - 1; i; i--) cnt[i] += cnt[i + 1];
  int mul = 1;
  for (int i = 1; i <= n; i++) {
    if (cnt[i] <= n - i) return puts("0"), 0;
    mul = 1ll * mul * (cnt[i] - (n - i)) % mod;
  }
  build(1, 1, n);
  int ans = 0;
  for (int j = n; j; j--) {
    for (int i : V[j]) {
      pair<int, int> ret = query(1, 1, n, i, n);
      ans = (ans + 1ll * ret.first * inv2 % mod);
      ret = query(1, 1, n, 1, i);
      ans = ((ans + 1ll * ret.second * mul % mod) % mod -
             1ll * ret.first * inv2 % mod + mod) %
            mod;
    }
    int sz = V[j].size();
    ans = (ans +
           1ll * sz * (sz - 1) % mod * inv2 % mod * mul % mod * inv2 % mod) %
          mod;
    for (int i : V[j]) update(1, 1, n, i, mul);
    int tmp =
        1ll * (cnt[j] - 1 - (n - j)) * qpow(cnt[j] - (n - j), mod - 2) % mod;
    modify(1, tmp);
  }
  printf("%d\n", ans);
  return 0;
}
