#include <bits/stdc++.h>
using namespace std;
inline int gi() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = (x << 3) + (x << 1) + ch - 48;
    ch = getchar();
  }
  return x * f;
}
template <typename T>
inline bool Max(T &a, T b) {
  return a < b ? a = b, 1 : 0;
}
template <typename T>
inline bool Min(T &a, T b) {
  return a > b ? a = b, 1 : 0;
}
const int N = 2e5 + 7, mod = 1e9 + 7;
const long long inv2 = 500000004ll;
int n;
int a[N], cnt[N], z[N], S[N];
long long tot = 1, D[N], t1[N], t2[N], ans;
long long Pow(long long a, long long b) {
  long long res = 1ll;
  for (; b; b >>= 1, a = a * a % mod)
    if (b & 1) res = res * a % mod;
  return res;
}
long long Inv(long long a) { return Pow(a, mod - 2); }
int lowbit(int x) { return x & -x; }
void c1(int x, long long y) {
  for (int i = x; i <= n; i += lowbit(i)) t1[i] = (t1[i] + y) % mod;
}
long long q1(long long x) {
  long long res = 0;
  for (int i = x; i; i -= lowbit(i)) res = (res + t1[i]) % mod;
  return res;
}
long long q1(int l, int r) {
  if (l > r) return 0;
  return ((q1(r) - q1(l - 1)) % mod + mod) % mod;
}
void c2(int x, int y) {
  for (int i = x; i <= n; i += lowbit(i)) t2[i] += y;
}
int q2(int x) {
  int res = 0;
  for (int i = x; i; i -= lowbit(i)) res += t2[i];
  return res;
}
int q2(int l, int r) {
  if (l > r) return 0;
  return q2(r) - q2(l - 1);
}
void add(long long &a, long long b) {
  a += b;
  if (a >= mod) a -= mod;
}
int main() {
  n = gi();
  for (int i = 1; i <= n; ++i) ++cnt[a[i] = gi()];
  for (int i = n - 1; i; --i) cnt[i] += cnt[i + 1];
  for (int i = 1; i <= n; ++i) cnt[i] -= n - i;
  for (int i = 1; i <= n; ++i) tot = tot * cnt[i] % mod;
  if (!tot) return puts("0"), 0;
  D[0] = 1;
  for (int i = 1; i <= n; ++i) {
    long long x = 1ll * (cnt[i] - 1) * Inv(cnt[i]) % mod;
    z[i] = z[i - 1], D[i] = D[i - 1];
    if (!x)
      S[++z[i]] = i;
    else
      D[i] = D[i] * x % mod;
  }
  for (int i = 1; i <= n; ++i) {
    (ans += (q1(1, a[i]) - (z[a[i]] == 1 ? 0 : q1(1, S[z[a[i]]]))) * D[a[i]] %
            mod * inv2 % mod * tot % mod) %= mod;
    c1(a[i], Inv(D[a[i]]));
  }
  memset(t1, 0, sizeof t1);
  for (int i = 1; i <= n; ++i) {
    ans -= (q1(a[i] + 1, n) - (!S[z[a[i]] + 1] ? 0 : q1(S[z[a[i]] + 1], n))) *
           Inv(D[a[i]]) % mod * inv2 % mod * tot % mod;
    add(ans, tot * q2(a[i] + 1, n) % mod);
    c1(a[i], D[a[i]]);
    c2(a[i], 1);
  }
  printf("%lld\n", (ans % mod + mod) % mod);
  return 0;
}
