#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long N = 1 << 18;
long long n, ans, all;
long long w[N];
long long A[N];
long long p0[N];
long long p1[N];
long long moge[N];
long long fpow(long long a, long long b) {
  long long res = 1;
  while (b) {
    if (b & 1) res = res * a % mod;
    a = a * a % mod;
    b /= 2;
  }
  return res;
}
struct tree {
  long long load[2 * N];
  void insert(long long a, long long v) {
    a += N;
    while (a) {
      load[a] += v;
      load[a] %= mod;
      a /= 2;
    }
  }
  long long query(long long a, long long b) {
    if (a > b) return 0;
    a += N;
    b += N;
    long long res = load[a];
    if (a != b) {
      res += load[b];
      res %= mod;
    }
    while (a < b - 1) {
      if (a % 2 == 0) {
        res += load[a + 1];
        res %= mod;
      }
      if (b % 2 == 1) {
        res += load[b - 1];
        res %= mod;
      }
      a /= 2;
      b /= 2;
    }
    return res;
  }
};
tree T, cnt;
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cin >> n;
  for (long long i = 1; i <= n; ++i) {
    cin >> A[i];
    ++w[A[i]];
  }
  for (long long i = n; i >= 1; --i) {
    w[i] += w[i + 1];
  }
  for (long long i = n; i >= 1; --i) {
    w[i] -= n - i;
  }
  p0[0] = p1[0] = 1;
  moge[0] = 1;
  for (long long i = 1; i <= n; ++i) {
    p0[i] = p0[i - 1] * w[i] % mod;
    p1[i] = p1[i - 1] * (w[i] - 1) % mod;
    if (p1[i] == 0) {
      p0[i] = p1[i] = 1;
      moge[i] = i;
    } else
      moge[i] = moge[i - 1];
  }
  all = p0[n];
  if (!all) {
    cout << 0 << '\n';
    return 0;
  }
  for (long long i = 1; i <= n; ++i) {
    long long z0 = fpow(p1[i], mod - 2) * p0[i] % mod;
    long long z1 = fpow(p0[i], mod - 2) * p1[i] % mod;
    p0[i] = z0;
    p1[i] = z1;
  }
  for (long long i = 1; i <= n; ++i) {
    ans += all * cnt.query(A[i], n) % mod;
    ans += p1[A[i]] * T.query(moge[A[i]], A[i] - 1) % mod;
    ans %= mod;
    T.insert(A[i], all * p0[A[i]] % mod * fpow(2, mod - 2) % mod);
    cnt.insert(A[i], 1);
  }
  memset(T.load, 0, sizeof T.load);
  for (long long i = n; i >= 1; --i) {
    ans += p1[A[i]] * T.query(moge[A[i]], A[i]) % mod;
    ans %= mod;
    T.insert(A[i], -all * p0[A[i]] % mod * fpow(2, mod - 2) % mod);
  }
  ans += mod;
  ans %= mod;
  cout << ans << '\n';
}
