#include <bits/stdc++.h>
using namespace std;
const int N = 200050, mo = 1e9 + 7, ni = (mo + 1) / 2;
int gi() {
  char ch = getchar();
  int x = 0, q = 0;
  while (ch < '0' || ch > '9') q = ch == '-' ? 1 : q, ch = getchar();
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return q ? -x : x;
}
int fap(int a, int b) {
  int s = 1;
  for (; b; b >>= 1, a = 1ll * a * a % mo)
    if (b & 1) s = 1ll * s * a % mo;
  return s;
}
int n, ans, num[N], a[N], d[N], cnt[N], w[N], L[N], R[N];
struct bit {
  int f[N];
  void ins(int x, int s) {
    while (x <= n) (f[x] += s) %= mo, x += x & -x;
    return;
  }
  int query(int x) {
    int s = 0;
    while (x) (s += f[x]) %= mo, x -= x & -x;
    return s;
  }
} A, B, C;
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) a[i] = gi(), ++cnt[a[i]];
  for (int i = n - 1; i; --i) cnt[i] += cnt[i + 1] - 1;
  for (int i = 1; i <= n; ++i)
    if (cnt[i] <= 0) return puts("0"), 0;
  int sum = 1;
  d[0] = 1;
  for (int i = 1; i <= n; ++i) {
    num[i] = num[i - 1], d[i] = d[i - 1], sum = 1ll * sum * cnt[i] % mo;
    if (cnt[i] == 1)
      ++num[i];
    else
      d[i] = 1ll * d[i] * (cnt[i] - 1) % mo * fap(cnt[i], mo - 2) % mo;
    w[i] = fap(d[i], mo - 2);
  }
  R[n + 1] = n + 1, num[n + 1] = num[n];
  for (int i = 1; i <= n; ++i)
    if (num[i] == num[i - 1])
      L[i] = L[i - 1];
    else
      L[i] = i;
  for (int i = n; i >= 1; --i)
    if (num[i] == num[i + 1])
      R[i] = R[i + 1];
    else
      R[i] = i;
  int s, v;
  for (int i = 1; i <= n; ++i) {
    s = (mo + A.query(a[i]) - A.query(L[a[i]])) % mo;
    (ans += 1ll * s * d[a[i]] % mo * sum % mo * ni % mo) %= mo;
    if (R[a[i] + 1] > a[i] + 1)
      s = (mo + B.query(R[a[i] + 1] - 1) - B.query(a[i])) % mo;
    else
      s = 0;
    v = (mo + C.query(n) - C.query(a[i])) % mo;
    (ans += 1ll * sum * v % mo) %= mo;
    (ans += mo - 1ll * s * w[a[i]] % mo * ni % mo * sum % mo) %= mo;
    A.ins(a[i], w[a[i]]), B.ins(a[i], d[a[i]]), C.ins(a[i], 1);
  }
  cout << ans;
  return 0;
}
