#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
const int mod = 1e9 + 7;
int n, tot;
int a[maxn], val[maxn], cnt[maxn], prod[maxn], iprod[maxn], inv[maxn];
int quickpow(int x, int pow) {
  int res = 1;
  for (; pow; pow >>= 1) {
    if (pow & 1) res = 1LL * res * x % mod;
    x = 1LL * x * x % mod;
  }
  return res;
}
class Fenwick {
 public:
  int t[maxn];
  void clear() {
    for (int i = 1; i <= (n); i++) t[i] = 0;
  }
  void add(int v, int val) {
    for (; v <= n; v += (v & -v)) {
      t[v] += val;
      if (t[v] >= mod) t[v] -= mod;
    }
  }
  int sum(int v) {
    int res = 0;
    for (; v; v -= (v & -v)) {
      res += t[v];
      if (res >= mod) res -= mod;
    }
    return res;
  }
} Sum, Cnt;
int main() {
  scanf("%d", &n);
  inv[0] = inv[1] = 1;
  for (int i = 2; i <= n; i++)
    inv[i] = 1LL * inv[mod % i] * (mod - mod / i) % mod;
  tot = 1;
  for (int i = 1; i <= (n); i++) {
    scanf("%d", &a[i]);
    cnt[a[i]]++;
  }
  int s = 0;
  for (int i = n; i >= 1; i--) {
    s += cnt[i];
    val[i] = s - (n - i);
    if (val[i] <= 0) {
      puts("0");
      return 0;
    }
    tot = 1LL * tot * val[i] % mod;
    val[i] = 1LL * (val[i] - 1) * inv[val[i]] % mod;
  }
  prod[0] = iprod[0] = 1;
  for (int i = 1; i <= (n); i++) {
    int tmp = max(val[i], 1);
    prod[i] = 1LL * prod[i - 1] * tmp % mod;
    iprod[i] = 1LL * iprod[i - 1] * quickpow(tmp, mod - 2) % mod;
  }
  int ans = 0;
  for (int i = 1; i <= (n); i++) {
    ans += 1LL * cnt[i] * (cnt[i] - 1) / 2 % mod * tot % mod;
    if (ans >= mod) ans -= mod;
  }
  if (ans & 1) ans += mod;
  ans /= 2;
  int last = 1;
  for (int i = 1; i <= (n); i++) {
    if (!val[a[i]]) {
      for (int j = last; j < i; j++) Sum.add(a[j], (mod - iprod[a[j]]) % mod);
      last = i;
    } else {
      int cur = 1LL * prod[a[i]] * Sum.sum(a[i] - 1) % mod * tot % mod;
      if (cur & 1) cur += mod;
      cur /= 2;
      ans += cur;
      if (ans >= mod) ans -= mod;
    }
    Sum.add(a[i], iprod[a[i]]);
  }
  Sum.clear();
  last = n;
  for (int i = n; i >= 1; i--) {
    ans += 1LL * Cnt.sum(a[i] - 1) * tot % mod;
    if (ans >= mod) ans -= mod;
    Cnt.add(a[i], 1);
    if (!val[a[i]]) {
      for (int j = last; j > i; j--) Sum.add(a[j], (mod - iprod[a[j]]) % mod);
      last = i;
    } else {
      int cur = 1LL * prod[a[i]] * Sum.sum(a[i] - 1) % mod * tot % mod;
      if (cur & 1) cur += mod;
      cur /= 2;
      ans -= cur;
      if (ans < 0) ans += mod;
    }
    Sum.add(a[i], iprod[a[i]]);
  }
  printf("%d\n", ans);
  return 0;
}
