#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
template<typename T> inline void chkmin(T &a, const T &b) { a = a < b ? a : b; }
template<typename T> inline void chkmax(T &a, const T &b) { a = a > b ? a : b; }

const int MAXN = 200005, MAXT = 1 << 19, MOD = 1e9 + 7;
inline int add(int a, int b) { a += b - MOD; return a + (a >> 31 & MOD); }
LL modpow(LL a, int b) {
	LL res = 1;
	for (; b; b >>= 1) {
		if (b & 1) res = res * a % MOD;
		a = a * a % MOD;
	}
	return res;
}

int sum[MAXT], cnt[MAXT], tag[MAXT], A[MAXN], suf[MAXN], n;
vector<int> pla[MAXN];
void push_up(int k) {
	sum[k] = add(sum[k << 1], sum[k << 1 | 1]);
	cnt[k] = cnt[k << 1] + cnt[k << 1 | 1];
}
void cover(int k, int t) {
	tag[k] = (LL)tag[k] * t % MOD;
	sum[k] = (LL)sum[k] * t % MOD;
}
void push_down(int k) {
	if (tag[k] == 1) return;
	int &t = tag[k];
	cover(k << 1, t), cover(k << 1 | 1, t);
	t = 1;
}

void modify(int p, int x, int l = 1, int r = n, int k = 1) {
	if (l == r) { sum[k] = x, cnt[k] = 1; return; }
	int mid = (l + r) >> 1;
	push_down(k);
	if (p <= mid) modify(p, x, l, mid, k << 1);
	else modify(p, x, mid + 1, r, k << 1 | 1);
	push_up(k);
}

int query(int a, int b, int l = 1, int r = n, int k = 1) {
	if (a > r || b < l) return 0;
	if (a <= l && b >= r) return sum[k];
	int mid = (l + r) >> 1;
	push_down(k);
	return add(query(a, b, l, mid, k << 1), query(a, b, mid + 1, r, k << 1 | 1));
}

int gsum(int a, int b, int l = 1, int r = n, int k = 1) {
	if (a > r || b < l) return 0;
	if (a <= l && b >= r) return cnt[k];
	int mid = (l + r) >> 1;
	return gsum(a, b, l, mid, k << 1) + gsum(a, b, mid + 1, r, k << 1 | 1);
}

int main() {
	fill(tag, tag + MAXT, 1);
	scanf("%d", &n);
	if (n == 1) return puts("0"), 0;
	for (int i = 1; i <= n; i++) {
		scanf("%d", A + i);
		++suf[A[i]];
		pla[A[i]].push_back(i);
	}
	for (int i = n; i > 0; i--) suf[i] += suf[i + 1];
	LL prod = 1, ans = 0;
	const LL inv2 = (MOD + 1) / 2;
	for (int i = 1; i <= n; i++) {
		suf[i] -= n - i;
		if (suf[i] <= 0) return puts("0"), 0;
		prod = prod * suf[i] % MOD;
	}
	for (int i = n; i > 0; i--) {
		LL mul = (suf[i] - 1) * modpow(suf[i], MOD - 2) % MOD;
		for (int j : pla[i])
			ans = (ans + prod * gsum(1, j) + (query(j, n) - query(1, j) + MOD) * inv2) % MOD;
		int sz = pla[i].size();
		ans = (ans + (LL)sz * (sz - 1) / 2 % MOD * prod % MOD * inv2) % MOD;
		for (int j : pla[i]) modify(j, prod);
		cover(1, mul);
	}
	printf("%lld\n", ans);
	return 0;
}