#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
const int mod = 1000000007;
inline int qp(int a, int b) {
	int res = 1;
	while (b) {
		if (b & 1) res = 1ll * res * a % mod;
		a = 1ll * a * a % mod;
		b >>= 1;
	}
	return res;
}
struct Num {
	int val, e0;
	inline Num(int _v = 0, int _0 = 0): val(_v), e0(_0) {}
	inline Num operator + (const Num &oth) const {
		return Num((val + oth.val) % mod, 0);
	}
	inline Num operator * (const Num &oth) const {
		return Num(1ll * val * oth.val % mod, e0 + oth.e0);
	}
};
int n, a[N];
int Cnt[N], L[N], R[N];
Num D[N], bit[N];
int bit2[N];
inline void add2(int i) {
	while (i <= n) {
		bit2[i]++;
		i += i & -i;
	}
}
inline int sum2(int i) {
	int res = 0;
	while (i > 0) {
		res += bit2[i];
		i -= i & -i;
	}
	return res;
}
inline void add(int i, Num x) {
	while (i <= n) {
		bit[i] = bit[i] + x;
		i += i & -i;
	}
}
inline int sum(int i) {
	Num res;
	while (i > 0) {
		res = res + bit[i];
		i -= i & -i;
	}
	return res.val;
}
int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		Cnt[a[i]]++;
	}
	for (int i = n; i >= 1; i--) {
		Cnt[i] += Cnt[i + 1];
	}
	int cp = 1;
	D[0] = 1;
	for (int i = 1; i <= n; i++) {
		Cnt[i] -= n - i;
		if (Cnt[i] < 1) { puts("0"); return 0; }
		cp = 1ll * cp * Cnt[i] % mod;
		Num cur = qp(Cnt[i], mod - 2);
		if (Cnt[i] == 1) cur.e0 = 1;
		else cur = cur * (Cnt[i] - 1);
		D[i] = D[i - 1] * cur;
		if (i == 1 || D[i].e0 != D[i - 1].e0) L[i] = i;
		else L[i] = L[i - 1];
	}
	for (int i = n; i; i--) {
		if (i == n || D[i].e0 != D[i + 1].e0) R[i] = i;
		else R[i] = R[i + 1];
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		ans = (ans + 1ll * (sum(a[i]) - sum(L[a[i]] - 1) + mod) * D[a[i]].val % mod * cp % mod) % mod;
		add(a[i], Num(qp(D[a[i]].val, mod - 2), D[a[i]].e0));
	}
	if (ans & 1) ans += mod;
	ans >>= 1;
	for (int i = 1; i <= n; i++) bit[i] = 0;
	for (int i = 1; i <= n; i++) {
		ans = (ans + 1ll * cp * (i - 1 - sum2(a[i])) % mod) % mod;
		int fuck = 1ll * (sum(R[a[i]]) - sum(a[i]) + mod) * qp(D[a[i]].val, mod - 2) % mod * cp % mod;
		if (fuck & 1) fuck += mod;
		fuck >>= 1;
		ans = (ans - fuck + mod) % mod;
		add(a[i], D[a[i]]);
		add2(a[i]);
	}
	printf("%d\n", ans);
	return 0;
}