#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int add(int x, int y) { return x + y < mod ? x + y : x + y - mod; }
void ade(int &x, int y) {
  x += y;
  if (x >= mod) x -= mod;
}
int qpow(int x, int k) {
  int r = 1;
  while (k) {
    if (k & 1) r = 1ll * r * x % mod;
    k >>= 1;
    x = 1ll * x * x % mod;
  }
  return r;
}
int n;
int a[200200];
int d[200200];
int D[200200];
struct Node {
  int sum, cnt;
  Node operator+(const Node &o) const {
    Node res;
    res.sum = add(sum, o.sum);
    res.cnt = cnt + o.cnt;
    return res;
  }
  Node operator-(const Node &o) const {
    Node res;
    res.sum = add(sum, mod - o.sum);
    res.cnt = cnt - o.cnt;
    return res;
  }
};
struct Bit {
  Node C[2000200];
  int lb(int x) { return x & (-x); }
  void ins(int x, Node v) {
    while (x <= n) C[x] = C[x] + v, x += lb(x);
  }
  void clear(int x) {
    while (x <= n) C[x] = (Node){0, 0}, x += lb(x);
  }
  Node ask(int x) {
    Node r;
    r.sum = r.cnt = 0;
    while (x) r = r + C[x], x -= lb(x);
    return r;
  }
  Node query(int l, int r) { return ask(r) - ask(l - 1); }
} bit;
struct B2 {
  int C[2000200];
  int lb(int x) { return x & (-x); }
  void ins(int x) {
    while (x <= n) C[x]++, x += lb(x);
  }
  int ask(int x) {
    int r = 0;
    while (x) r += C[x], x -= lb(x);
    return r;
  }
  int query(int l, int r) { return ask(r) - ask(l - 1); }
} b2;
int pos[200200];
bool cmp(int x, int y) { return a[x] < a[y]; }
bool zero[200200];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), d[a[i]]++, pos[i] = i;
  for (int i = n; i; --i) d[i] += d[i + 1];
  int S = 1;
  D[0] = 1;
  for (int i = 1; i <= n; ++i) {
    d[i] = max(0, d[i] - n + i);
    int tmp = 1ll * (d[i] - 1) * qpow(d[i], mod - 2) % mod;
    if (!tmp)
      zero[i] = 1, D[i] = D[i - 1];
    else
      D[i] = 1ll * D[i - 1] * tmp % mod;
    S = 1ll * S * d[i] % mod;
  }
  if (!S) {
    puts("0");
    return 0;
  }
  sort(pos + 1, pos + n + 1, cmp);
  int p, ans = 0;
  int mul, sum;
  int inv2 = qpow(2, mod - 2);
  Node cur;
  for (int i = 1, la = 0; i <= n; ++i) {
    p = pos[i];
    if (zero[a[p]]) {
      ade(ans, 1ll * b2.query(p + 1, n) * S % mod);
      b2.ins(p);
      for (int j = la + 1; j < i; ++j) bit.clear(pos[j]);
      la = i;
      continue;
    }
    mul = 1ll * S * D[a[p]] % mod;
    cur = bit.query(1, p - 1);
    ade(ans, 1ll * cur.sum * mul % mod * inv2 % mod);
    cur = bit.query(p + 1, n);
    ade(ans, 1ll * b2.query(p + 1, n) * S % mod);
    ade(ans, mod - 1ll * cur.sum * mul % mod * inv2 % mod);
    bit.ins(p, (Node){qpow(D[a[p]], mod - 2), 1});
    b2.ins(p);
  }
  printf("%d\n", ans);
  return 0;
}
