# include <bits/stdc++.h>
using namespace std;
typedef long long ll;

namespace IO {
    const int maxn((1 << 21) + 1);

    char ibuf[maxn], *iS, *iT, c;
    int f, tp;

    inline char Getc() {
        return (iS == iT ? (iT = (iS = ibuf) + fread(ibuf, 1, maxn, stdin), (iS == iT ? EOF : *iS++)) : *iS++);
    }
    
    template <class Int> inline void Input(Int &x) {
        for (f = 1, c = Getc(); c < '0' || c > '9'; c = Getc()) f = c == '-' ? -1 : 1;
        for (x = 0; c <= '9' && c >= '0'; c = Getc()) x = (x << 3) + (x << 1) + (c ^ 48);
        x *= f;
    }
}

using IO :: Input;

const int maxn(2e5 + 5);
const int mod(1e9 + 7);

int n, a[maxn], t[maxn], ans, lst[maxn], id[maxn], half;
int inv[maxn], cnt[maxn], icnt[maxn], acnt, c1[maxn], c2[maxn];

inline void Inc(int &x, const int y) {
	x += y;
	if (x >= mod) x -= mod;
}

inline void Add(int *c, int x, const int v) {
	for (; x <= n; x += x & -x) Inc(c[x], v);
}

inline int Query(int *c, int x) {
	int ret = 0;
	for (x = max(0, x); x; x -= x & -x) Inc(ret, c[x]);
	return ret;
}

inline bool Cmp(int x, int y) {
	return a[x] == a[y] ? x < y : a[x] < a[y];
}

int main() {
	Input(n);
	acnt = icnt[0] = cnt[0] = inv[0] = inv[1] = 1;
	for (int i = 2; i <= n; ++i) inv[i] = 1LL * (mod - mod / i) * inv[mod % i] % mod;
	for (int i = 1; i <= n; ++i) Input(a[i]), ++t[a[i] = min(a[i], n)];
	for (int i = n; i; --i) t[i] += t[i + 1];
	for (int i = 1; i <= n; ++i) {
		int cur = t[i] - (n - i);
		if (cur <= 0) return puts("0"), 0;
		cnt[i] = 1LL * cnt[i - 1] * cur % mod;
		icnt[i] = 1LL * icnt[i - 1] * inv[cur] % mod;
		acnt = 1LL * cur * acnt % mod;
		lst[i] = lst[i - 1];
		if (cur > 1) {
			icnt[i] = 1LL * icnt[i] * (cur - 1) % mod;
			cnt[i] = 1LL * cnt[i] * inv[cur - 1] % mod;
		}
		else lst[i] = i;
	}
	half = 1LL * acnt * inv[2] % mod;
	for (int i = 1; i <= n; ++i) {
		int cur = half, sum;
		sum = Query(c2, a[i]);
		Inc(sum, mod - Query(c2, lst[a[i]] - 1));
		cur = 1LL * cur * icnt[a[i]] % mod * sum % mod;
		Inc(ans, cur);
		Add(c2, a[i], cnt[a[i]]);
	}
	for (int i = 1; i <= n; ++i) c1[i] = c2[i] = 0;
	for (int i = n; i; --i) {
		int cur = half, sum;
		sum = Query(c1, a[i] - 1);
		Inc(ans, 1LL * acnt * sum % mod);
		sum = (Query(c2, a[i] - 1) - Query(c2, lst[a[i]] - 1) + mod) % mod;
		cur = 1LL * cur * icnt[a[i]] % mod * sum % mod;
		Inc(ans, mod - cur);
		Add(c1, a[i], 1), Add(c2, a[i], cnt[a[i]]);
	}
	printf("%d\n", ans);
	return 0;
}