#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 50, P = 1e9 + 7;
int mul(int a, int b) { return 1ll * a * b % P; }
int mul(int a, int b, int c) { return mul(a, mul(b, c)); }
int add(int a, int b) {
  a += b;
  return a >= P ? a - P : a;
}
int sub(int a, int b) {
  a -= b;
  return a < 0 ? a + P : a;
}
int power(int a, int k) {
  int res = 1;
  for (; k; k >>= 1, a = mul(a, a)) {
    if (k & 1) {
      res = mul(res, a);
    }
  }
  return res;
}
int inverse(int x) { return power(x, P - 2); }
int n, a[N], g[N], cnt[N], ans, L[N], R[N];
struct BinaryIndexedTree {
  int c[N], res;
  void update(int p, int k) {
    for (; p <= n; p += p & -p) c[p] = add(c[p], k);
  }
  int query(int p) {
    for (res = 0; p >= 1; p -= p & -p) res = add(res, c[p]);
    return res;
  }
  void clear() { memset(c, 0, sizeof(c)); }
} trG, trC;
int main(int argc, char *argv[]) {
  cin >> n;
  for (int i = 1; i <= (n); ++i) {
    cin >> a[i];
    ++cnt[a[i]];
  }
  for (int i = n - 1; i >= (1); --i) cnt[i] += cnt[i + 1];
  int prod = 1;
  for (int i = 1; i <= (n); ++i) {
    cnt[i] -= n - i;
    if (cnt[i] <= 0) {
      puts("0");
      return 0;
    };
    prod = mul(prod, cnt[i]);
    if (i == 1 || cnt[i] == 1) {
      L[i] = i;
      g[i] = 1;
    } else {
      L[i] = L[i - 1];
      g[i] = mul(cnt[i] - 1, inverse(cnt[i]));
      g[i] = mul(g[i - 1], g[i]);
    }
  };
  for (int i = n; i >= (1); --i) {
    if (i == n || cnt[i] == 1)
      R[i] = i;
    else
      R[i] = R[i + 1];
    ;
  }
  for (int i = 1; i <= (n); ++i) {
    int up = mul(g[a[i]], sub(trG.query(a[i]), trG.query(L[a[i]] - 1)));
    ans = add(ans, mul(prod, up, inverse(2)));
    trG.update(a[i], inverse(g[a[i]]));
    ;
  };
  trG.clear();
  for (int i = 1; i <= (n); ++i) {
    int tot = mul(prod, sub(trC.query(n), trC.query(a[i])));
    int unl = mul(
        prod, mul(inverse(g[a[i]]), sub(trG.query(R[a[i]]), trG.query(a[i]))),
        inverse(2));
    ans = add(ans, sub(tot, unl));
    trG.update(a[i], g[a[i]]);
    trC.update(a[i], 1);
    ;
    ;
  }
  printf("%d\n", ans);
  return 0;
}
