#include <stdio.h>
#include <vector>
using namespace std;

const long long mod = 1000000007;
const long long inv2 = (mod + 1) / 2;

int N, A[200200], C[200200];
long long E, Z, P[200200], S[200200], T[200200];
vector<int> I[200200];

vector<int> go(int l, int r)
{
	if (l == r){
		long long n = I[l].size();
		Z = (Z + E * (n * (n - 1) / 2 % mod) % mod * inv2) % mod;
		return I[l];
	}

	int m = (l + r) / 2;
	auto p = go(l, m);
	auto q = go(m + 1, r);
	vector<int> v;

	T[m] = 1;
	for (int i = m - 1; i >= l; i--) T[i] = T[i + 1] * (C[i + 1] - 1) % mod;
	for (int i = m + 1; i <= r; i++) T[i] = T[i - 1] * (C[i] - 1) % mod;
	for (int i = m; i >= l; i--) T[i] = T[i] * P[i] % mod;
	for (int i = m + 1; i <= r; i++) T[i] = T[i] * S[i + 1] % mod;

	long long ps = 0, qs = 0;
	int i = 0, j = 0;
	while (i < p.size() || j < q.size()){
		if (j == q.size() || (i < p.size() && p[i] < q[j])){
			long long t = T[A[p[i]]];
			Z = (Z + j * E - t * qs % mod * inv2) % mod;
			ps = (ps + t) % mod;
			v.push_back(p[i]);
			i++;
		}
		else{
			long long t = T[A[q[j]]];
			Z = (Z + ps * t % mod * inv2) % mod;
			qs = (qs + t) % mod;
			v.push_back(q[j]);
			j++;
		}
	}
	return v;
}

int main()
{
	scanf ("%d", &N);
	for (int i = 1; i <= N; i++){
		scanf ("%d", &A[i]);
		C[A[i]]++;
	}

	for (int i = N; i >= 1; i--) C[i] += C[i + 1];
	for (int i = N; i >= 1; i--) C[i] -= N - i;

	for (int i = 1; i <= N; i++) if (C[i] <= 0){
		puts("0");
		return 0;
	}

	P[0] = 1;
	for (int i = 1; i <= N; i++) P[i] = P[i - 1] * C[i] % mod;
	S[N + 1] = 1;
	for (int i = N; i >= 1; i--) S[i] = S[i + 1] * C[i] % mod;
	
	E = P[N];
	Z = 0;
	for (int i = 1; i <= N; i++) I[A[i]].push_back(i);
	go(1, N);
	Z = (Z + mod) % mod;

	printf ("%lld\n", Z);

	return 0;
}