#include <bits/stdc++.h>

using namespace std;

#define foru(i, l, r) for(int i = l; i <= r; i++)
#define ford(i, r, l) for(int i = r; i >= l; i--)

int read() {
  int res = 0; char c = getchar();
  while(!isdigit(c)) c = getchar();
  while(isdigit(c)) res = res * 10 + c - '0', c = getchar();
  return res;
}

const int maxn = 2e5 + 5;
const int mod = 1e9 + 7, inv_2 = (mod + 1) / 2;
void Inc(int &x, int y) { x += y, x -= x >= mod ? mod : 0; }
void Dec(int &x, int y) { x -= y, x += x < 0 ? mod : 0; }
int inc(int x, int y) { return x + y >= mod ? x + y - mod : x + y; }
int dec(int x, int y) { return x < y ? x - y + mod : x - y; }
int mul(int x, int y) { return 1LL * x * y % mod; }
int fastpow(int base, int x) {
  int res = 1;
  while(x) {
    if(x & 1) res = mul(res, base);
    base = mul(base, base), x >>= 1;
  }
  return res;
}

struct Bit {
#define lb (-x & x)
  int tree[maxn], lim;
  void init(int _l = 0) { memset(tree, 0, sizeof(tree)), lim = _l; }
  void Add(int x, int v) { while(x <= lim) Inc(tree[x], v), x += lb; }
  int Query(int x) { int res = 0; while(x) Inc(res, tree[x]), x -= lb; return res; }
  int _S(int l, int r) { return dec(Query(r), Query(l - 1)); }
#undef lb
} tree[3];

int N, x, S, ans;
int a[maxn], f[maxn], g[maxn], h[maxn];
int t[maxn], L[maxn], R[maxn];

int main() {
  N = read();
  tree[0].init(N);
  tree[1].init(N);
  tree[2].init(N);
  foru(i, 1, N) f[a[i] = read()]++;
  ford(i, N, 1) f[i] += f[i + 1];
  foru(i, 1, N) if((f[i] -= N - i) <= 0) return puts("0"), 0;
  S = g[0] = 1;
  foru(i, 1, N) {
    g[i] = fastpow(f[i], mod - 2), t[i] = t[i - 1];
    if(f[i] == 1) t[i]++;
    else g[i] = mul(g[i], f[i] - 1);
    g[i] = mul(g[i], g[i - 1]);
    h[i] = fastpow(g[i], mod - 2);
    S = mul(S, f[i]);
  }
  t[0] = t[N + 1] = -1;
  foru(i, 1, N) L[i] = (t[i] == t[i - 1] ? L[i - 1] : i);
  ford(i, N, 1) R[i] = (t[i] == t[i + 1] ? R[i + 1] : i);
  foru(i, 1, N) {
    x = a[i];
    Inc(ans, mul(g[x], tree[0]._S(L[x], x)));
    Dec(ans, mul(h[x], tree[1]._S(x + 1, R[x])));
    Inc(ans, tree[2]._S(x + 1, N));
    tree[0].Add(x, h[x]);
    tree[1].Add(x, g[x]);
    tree[2].Add(x, 2);
  }
  ans = mul(ans, S);
  ans = mul(ans, inv_2);
  printf("%d\n", ans);
  return 0;
}
