#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
int N, A[200005], x[200005], st[200005], ed[200005];
long long cnt[200005], V[200005], D[200005], ID[200005], S, tr[200005],
    tr_cnt[200005], Inv_2, ans;
long long fpow(long long x, long long c) {
  long long res = 1, t = x;
  while (c) {
    if (c & 1) res = res * t % MOD;
    t = t * t % MOD;
    c >>= 1;
  }
  return res;
}
int lowbit(int x) { return x & (-x); }
void insert(int x, long long v) {
  while (x <= N) {
    tr[x] += v;
    tr[x] %= MOD;
    tr_cnt[x]++;
    x += lowbit(x);
  }
}
long long Query(int x, long long v) {
  long long res = 0;
  while (x > 0) {
    res += tr[x];
    x -= lowbit(x);
  }
  res %= MOD;
  return res * v % MOD;
}
long long getnum(int x) {
  long long res = 0;
  while (x > 0) {
    res += tr_cnt[x];
    x -= lowbit(x);
  }
  return res;
}
long long Query_range(int L, int R, long long v) {
  if (L == 0) ++L;
  if (L > R) return 0;
  return (Query(R, v) + MOD - Query(L - 1, v)) % MOD;
}
void Solve() {
  scanf("%d", &N);
  for (int i = 1; i <= N; ++i) scanf("%d", &A[i]), cnt[A[i]]++;
  for (int i = N - 1; i >= 1; --i) cnt[i] += cnt[i + 1];
  S = 1;
  Inv_2 = (MOD + 1) / 2;
  for (int i = 1; i <= N; ++i) {
    cnt[i] -= N - i;
    if (cnt[i] <= 0) {
      puts("0");
      return;
    }
    S = S * cnt[i] % MOD;
  }
  for (int i = 1; i <= N; ++i) {
    V[i] = (cnt[i] - 1) * fpow(cnt[i], MOD - 2) % MOD;
  }
  D[0] = 1;
  st[0] = 0;
  for (int i = 1; i <= N; ++i) {
    x[i] = x[i - 1];
    D[i] = D[i - 1];
    if (V[i] == 0) {
      x[i]++;
      st[x[i]] = i;
      ed[x[i] - 1] = i - 1;
    } else
      D[i] = D[i] * V[i] % MOD;
    ID[i] = fpow(D[i], MOD - 2);
  }
  ed[x[N]] = N;
  for (int i = 1; i <= N; ++i) {
    ans += Query_range(st[x[A[i]]], A[i], D[A[i]] * S % MOD * Inv_2 % MOD);
    ans %= MOD;
    insert(A[i], ID[A[i]]);
  }
  memset(tr, 0, sizeof(tr));
  memset(tr_cnt, 0, sizeof(tr_cnt));
  for (int i = 1; i <= N; ++i) {
    long long t =
        Query_range(A[i] + 1, ed[x[A[i]]], ID[A[i]] * S % MOD * Inv_2 % MOD);
    ans += ((getnum(N) - getnum(A[i])) * S % MOD + MOD - t) % MOD;
    ans %= MOD;
    insert(A[i], D[A[i]]);
  }
  printf("%lld\n", ans);
}
int main() {
  Solve();
  return 0;
}
