#include <bits/stdc++.h>
using namespace std;
long long read() {
  long long x = 0, f = 0;
  char ch = getchar();
  while (!isdigit(ch)) f = ch == '-', ch = getchar();
  while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
  return f ? -x : x;
}
const int N = 200005, mod = 1e9 + 7;
int inv2 = (mod + 1) / 2;
int Pow(int x, int y) {
  int ans = 1;
  for (; y; y >>= 1, x = (long long)x * x % mod)
    if (y & 1) ans = (long long)ans * x % mod;
  return ans;
}
void Add(int &x, int y) {
  if ((x += y) >= mod) x -= mod;
}
void Del(int &x, int y) {
  if ((x -= y) < 0) x += mod;
}
int Add(int x) { return x >= mod ? x - mod : x; }
int Del(int x) { return x < 0 ? x + mod : x; }
int n, S = 1;
int a[N], b[N], p[N];
namespace bit {
int c[N];
void add(int x, int d) {
  for (; x <= n; x += x & -x) Add(c[x], d);
}
int Ask(int x) {
  int ans = 0;
  for (; x; x -= x & -x) Add(ans, c[x]);
  return ans;
}
}  // namespace bit
bool cmp1(int x, int y) { return a[x] < a[y]; }
bool cmp2(int x, int y) { return x < y; }
int pre[N];
int main() {
  n = read();
  for (int i = (1); i <= (n); i++) {
    a[i] = read();
    b[a[i]]++;
  }
  for (int i = (n); i >= (1); i--) b[i] += b[i + 1];
  for (int i = (1); i <= (n); i++) b[i] -= n - i;
  for (int i = (1); i <= (n); i++) {
    if (b[i] <= 0) return puts("0"), 0;
    S = (long long)S * b[i] % mod;
  }
  for (int i = (1); i <= (n); i++) p[i] = i;
  sort(p + 1, p + n + 1, cmp1);
  int ans = 0;
  for (int i = 1, j; i <= n; i = j) {
    for (j = i + 1; j <= n; j++) {
      int flag = 0;
      for (int k = (a[p[j - 1]] + 1); k <= (a[p[j]]); k++)
        if (b[i] == 1) {
          flag = 1;
          break;
        }
      if (flag) break;
    }
    int mi = a[p[i]], mx = a[p[j - 1]];
    pre[mi] = 1;
    for (int k = (mi + 1); k <= (mx); k++)
      pre[k] =
          (long long)pre[k - 1] * (b[k] - 1) % mod * Pow(b[k], mod - 2) % mod;
    sort(p + i, p + j, cmp2);
    for (int k = (i); k <= (j - 1); k++) {
      int x = p[k];
      if (k > i) {
        int t = (long long)bit::Ask(a[x]) * pre[a[x]] % mod;
        Add(ans, (long long)t * S % mod * inv2 % mod);
      }
      bit::add(a[x], Pow(pre[a[x]], mod - 2));
    }
    for (int k = (i); k <= (j - 1); k++)
      bit::add(a[p[k]], Del(-Pow(pre[a[p[k]]], mod - 2)));
    for (int k = (i); k <= (j - 1); k++) {
      int x = p[k];
      if (k > i) {
        int t = Del(bit::Ask(n) - bit::Ask(a[x]));
        t = (long long)t * Pow(pre[a[x]], mod - 2) % mod;
        Del(ans, (long long)t * S % mod * inv2 % mod);
      }
      bit::add(a[x], pre[a[x]]);
    }
    for (int k = (i); k <= (j - 1); k++) bit::add(a[p[k]], Del(-pre[a[p[k]]]));
  }
  for (int i = (1); i <= (n); i++) {
    int t = bit::Ask(n) - bit::Ask(a[i]);
    bit::add(a[i], 1);
    Add(ans, (long long)S * t % mod);
  }
  cout << ans << endl;
  return 0;
}
