#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  for (; !isdigit(ch); ch = getchar()) {
    if (ch == '-') f = -1;
  }
  for (; !isdigit(ch); ch = getchar()) {
    x = x * 10 + ch - 48;
  }
  return x * f;
}
const int N = 2e5;
const int P = 1e9 + 7;
const long long INV2 = 5e8 + 4;
int a[N + 3];
int cnt[N + 3];
long long d[N + 3];
int num0[N + 3];
int n;
long long ans, tot;
long long quickpow(long long x, long long y) {
  long long cur = x, ret = 1ll;
  for (int i = 0; y; i++) {
    if (y & (1ll << i)) {
      y -= (1ll << i);
      ret = ret * cur % P;
    }
    cur = cur * cur % P;
  }
  return ret;
}
long long mulinv(long long x) { return quickpow(x, P - 2); }
struct BITree {
  long long bit[N + 3];
  void add(int u, long long x) {
    while (u <= n) {
      bit[u] = (bit[u] + x) % P;
      u += (u & (-u));
    }
  }
  long long query(int u) {
    long long ret = 0ll;
    while (u) {
      ret = (ret + bit[u]) % P;
      u -= (u & (-u));
    }
    return ret;
  }
  void clear() {
    for (int i = 1; i <= n; i++) bit[i] = 0ll;
  }
} bit1, bit2;
void solve(int l, int r) {
  for (int i = r; i >= l; i--) {
    long long tmp = (bit1.query(n) - bit1.query(a[i] - 1) + P) *
                    mulinv(d[a[i]]) % P * INV2 % P * tot % P;
    ans = (ans + tmp) % P;
    bit1.add(a[i], d[a[i]]);
  }
  for (int i = r; i >= l; i--) {
    bit1.add(a[i], P - d[a[i]]);
  }
  for (int i = l; i <= r; i++) {
    long long tmp2 = (bit2.query(n) - bit2.query(a[i]) + P) * mulinv(d[a[i]]) %
                     P * INV2 % P * tot % P;
    ans = (ans - tmp2 + P) % P;
    bit2.add(a[i], d[a[i]]);
  }
  for (int i = l; i <= r; i++) {
    bit2.add(a[i], P - d[a[i]]);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
  for (int i = 1; i <= n; i++) cnt[a[i]]++;
  for (int i = n - 1; i >= 1; i--) cnt[i] += cnt[i + 1];
  for (int i = 1; i <= n; i++) cnt[i] -= (n - i);
  tot = 1ll;
  for (int i = 1; i <= n; i++) tot = tot * cnt[i] % P;
  if (tot == 0) {
    puts("0");
    return 0;
  }
  d[0] = 1ll;
  for (int i = 1; i <= n; i++) {
    long long tmp = (bit1.query(n) - bit1.query(a[i]) + P) * tot % P;
    ans = (ans + tmp) % P;
    bit1.add(a[i], 1);
  }
  bit1.clear();
  for (int i = 1; i <= n; i++) {
    long long tmp = (cnt[i] - 1) * mulinv(cnt[i]) % P;
    if (tmp) {
      d[i] = d[i - 1] * tmp % P;
      num0[i] = num0[i - 1];
    } else {
      d[i] = d[i - 1];
      num0[i] = num0[i - 1] + 1;
    }
  }
  for (int i = 1; i <= n; i++) {
    int j = i;
    while (j < n && num0[j + 1] == num0[i]) {
      j++;
    }
    solve(i, j);
    i = j;
  }
  printf("%lld\n", ans);
  return 0;
}
