#include <cstring>
#include <cstdio>
#define MOD 1000000007
typedef long long ll;
inline ll quick_pow(ll a, int n)
{
	ll res = 1;
	while (n)
	{
		if (n & 1)
			res = res * a % MOD;
		a = a * a % MOD;
		n >>= 1;
	}
	return res;
}
int sum[200005], arr[200005], app[200005], pre[200005], val[200005], n;
inline void modify(int pos, int x)
{
	for (; pos <= n; pos += pos & -pos)
		(sum[pos] += x) %= MOD;
}
inline int query(int pos)
{
	int res = 0;
	for (; pos; pos -= pos & -pos)
		(res += sum[pos]) %= MOD;
	return res;
}
int main()
{
	// freopen("AGC023-E.in", "r", stdin);
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		scanf("%d", arr + i);
		app[arr[i]]++;
	}
	for (int i = n; i; i--)
		app[i] += app[i + 1];
	ll coef = 1, ans = 0;
	for (int i = 1; i <= n; i++)
	{
		app[i] -= n - i;
		if (app[i] <= 0)
		{
			puts("0");
			return 0;
		}
		if (app[i] == 1)
			pre[i] = i;
		else
		{
			pre[i] = pre[i - 1];
			val[i] = (ll)(app[i] - 1) * quick_pow(app[i], MOD - 2) % MOD;
			if (val[i - 1])
				val[i] = (ll)val[i] * val[i - 1] % MOD;
		}
		coef = coef * app[i] % MOD;
	}
	for (int i = 0; i < n; i++)
	{
		(ans += coef * (query(arr[i]) - query(pre[arr[i]])) % MOD * val[arr[i]]) %= MOD;
		modify(arr[i], quick_pow(val[arr[i]], MOD - 2));
	}
	memset(sum, 0, sizeof(sum));
	for (int i = 0; i < n; i++)
	{
		(ans += coef * (i - query(arr[i])) * 2) %= MOD;
		modify(arr[i], 1);
	}
	memset(sum, 0, sizeof(sum));
	for (int i = n - 1; i >= 0; i--)
	{
		if (val[arr[i]])
		{
			(ans -= coef * (query(arr[i] - 1) - query(pre[arr[i]])) % MOD * val[arr[i]]) %= MOD;
			modify(arr[i], quick_pow(val[arr[i]], MOD - 2));
		}
	}
	printf("%lld\n", (ans + MOD) * (MOD + 1) / 2 % MOD);
	return 0;
}
