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

typedef long long lint;
const int maxn = 2000005, mod = (int)1e9 + 7, inv2 = (mod + 1) >> 1;

int n, ans, a[maxn], cnt[maxn], S;
int D[maxn], invD[maxn];
int zero[maxn];

inline int gi()
{
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	int sum = 0;
	while ('0' <= c && c <= '9') sum = sum * 10 + c - 48, c = getchar();
	return sum;
}

inline int Pow(int x, int k)
{
	int ret = 1;
	while (k) {
		if (k & 1) ret = (lint)ret * x % mod;
		x = (lint)x * x % mod; k >>= 1;
	}
	return ret;
}

inline void inc(int &a, int b) {a + b >= mod ? a += b - mod : a += b;}
inline void dec(int &a, int b) {a - b >= 0 ? a -= b : a += mod - b;}

struct BIT
{

	int sum[maxn];
	
	void clear() {memset(sum + 1, 0, sizeof(int) * n);}
	void insert(int x, int a)
	{
		while (x <= n) {
			inc(sum[x], a);
			x += x & (-x);
		}
	}
    int query(int x)
	{
		int ret = 0;
		while (x) {
			inc(ret, sum[x]);
			x -= x & (-x);
		}
		return ret;
	}
	
} bit1, bit2;

int main()
{
	n = gi();
	for (int i = 1; i <= n; ++i) a[i] = gi(), ++cnt[a[i]];
	for (int i = n; i >= 1; --i) cnt[i] += cnt[i + 1];
	S = 1;
	for (int i = 1; i <= n; ++i) S = (lint)S * (cnt[i] - (n - i)) % mod;
	if (!S) {puts("0"); return 0;}

	zero[0] = D[0] = 1;
	for (int i = 1; i <= n; ++i) {
		D[i] = (lint)(cnt[i] - (n - i) - 1) * Pow(cnt[i] - (n - i), mod - 2) % mod;
		if (!D[i]) zero[i] = i, D[i] = D[i - 1];
		else zero[i] = zero[i - 1], D[i] = (lint)D[i - 1] * D[i] % mod;
		invD[i] = Pow(D[i], mod - 2);
	}

	for (int i = 1; i <= n; ++i) {
		inc(ans, (lint)(bit1.query(a[i]) - bit1.query(zero[a[i]] - 1) + mod) % mod * S % mod * D[a[i]] % mod * inv2 % mod);
		bit1.insert(a[i], invD[a[i]]);
	}

	bit1.clear();

	for (int i = n; i >= 1; --i) {
		dec(ans, (lint)(bit1.query(a[i] - 1) - bit1.query(zero[a[i]] - 1) + mod) % mod * S % mod * D[a[i]] % mod * inv2 % mod);
		inc(ans, (lint)bit2.query(a[i] - 1) * S % mod);
		bit1.insert(a[i], invD[a[i]]);
		bit2.insert(a[i], 1);
	}

	printf("%d\n", ans);
	
	return 0;
}
